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

二叉树深度计算
本文提供了二叉树最大深度和最小深度的计算方法,通过递归遍历左右子树来确定深度,对于最小深度的计算特别注意了叶子节点的情况。

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。做个判断即可。

转载于:https://www.cnblogs.com/ymjyqsx/p/10665608.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值