首页 > 其他 > 详细

leetcode 104. Maximum Depth of Binary Tree 111. Minimum Depth of Binary Tree

时间:2019-04-07 16:11:14      阅读:104      评论:0      收藏:0      [点我收藏+]

104:

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

111:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == NULL)
            return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        if(left == 0)
            return right + 1;
        else if(right == 0)
            return left + 1;
        else
            return left < right ? left + 1 : right + 1;
    }
};

最小的深度这个题与最大的深度这个题稍稍有点不同,因为最小深度的计算必须从叶子节点开始,没有叶子节点不能计算,所以1,2这种情况只能返回2,不能返回1。做个判断即可。

leetcode 104. Maximum Depth of Binary Tree 111. Minimum Depth of Binary Tree

原文:https://www.cnblogs.com/ymjyqsx/p/10665608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!