LeetCode-104 Maximum Depth of Binary Tree 二叉树的最大深度

时间:2021-09-29 17:29:12

给一个二叉树,求数的最大深度。

数据结构基础题,课本典型方法解决。对于每一个节点而言,深度都为当前深度 + 子节点深度,所以可以按此规律向下探索。

题目链接

class Solution {
public:
int depth = 0;
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
if (root->left) {
if (root->right) {
return max(1+maxDepth(root->left), 1+maxDepth(root->right));
}
else {
return 1 + maxDepth(root->left);
}
}
else {
if (root->right) {
return 1 + maxDepth(root->right);
}
else {
return 1;
}
}
}
};


相关文章