LeetCode111. 二叉树的最小深度
和104比较,这题有所不同
LeetCode104. 二叉树的最大深度
第一次做尝试直接照搬104,写出错误代码:
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root)return 0;
return min(minDepth(root->left) + 1, minDepth(root->right) + 1);
}
};
发现当一侧子树为空,一侧不为空时会错误返回当前层的值
故要单独讨论两侧子树的情况
代码:
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
if (!root->left && root->right) return 1 + rightDepth;
else if (root->left && !root->right) return 1 + leftDepth;
else return 1 + min(leftDepth, rightDepth);
}
};