104. 二叉树的最大深度
- 这一题看似简单但把二叉树前中后序的运算体现的淋漓尽致
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==nullptr)return 0;
int leftheight=maxDepth(root->left);
int rightheight=maxDepth(root->right);
return max(leftheight,rightheight)+1;
}
};
从底往上计数,每一层返回当前层的层数
111. 二叉树的最小深度
这一题差一点点做出来,下面来分析一下:
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==nullptr)return 0;
int leftheight=minDepth(root->left);
int rightheight=minDepth(root->right);
if(root->left==nullptr&&root->right!=nullptr)return rightheight+1;
if(root->right==nullptr&&root->left!=nullptr)return leftheight+1;
return min(leftheight,rightheight)+1;
}
};
这一题和上一题极为类似,区别在左右子树是否为空。如果左子树为空,那么返回值最小肯定就是1,不满足题目要求(到叶子的距离)。所以要判断左右子树为空的情况。但是问题出在你先定义了leftheight和rightheight,没有把握好这两个参数的值。如果对代码了解当然更深入当然不用这么麻烦。