111. Minimum Depth of Binary Tree


Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.


之前有一道求最大深度的题目

二叉树的最大深度

class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;

return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};

此题本以为把max改为min就可以了,后来发现有坑,二叉树最小深度指的是树的叶节点的最小深度,如果只是改为min的话,在树只有右子树的情况下,它的深度就为1了,但其实不对。所以应该判断是否为叶节点,若为叶节点则直接返回深度,若不是则继续遍历非空的子树。

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root)
            return 0;
        if(!root->left&&!root->right)
            return 1;
        if(!root->left) return minDepth(root->right)+1;
        if(!root->right) return minDepth(root->left)+1;
        return min(minDepth(root->left),minDepth(root->right))+1;
    }
};

猜你喜欢

转载自blog.csdn.net/jifeng7288/article/details/79909077