LeetCode 之 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.

不就是求二叉树从根节点到叶子节点的最小深度么。。。。这个题跟这个题非常像二叉树的最大深度,学渣就是抱着这种心态犯了一个大错。。。。

思路如下:

1 采用递归,判断当前节点是否为空,是空返回0

2 利用递归,返回左右节点较小的路径数+1

代码如下(错的):

class Solution {
public:
    int minDepth(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(root==NULL) return 1;
        else {
            int left = minDepth(root->left);
            int right = minDepth(root->right);
            
            return left>right?right+1:left+1;
        }
    }
};

这个得到wrong answer。。。。非常郁闷,看了别人的代码,恍然大悟。。。。上述代码有这么个错误,当左右节点有一个为空时,可能有两种情况:

1 左右都为0,返回大子树和小子树的结果一样,都是0

2 有一个为空,一个不为空,即left*right==0,返回较大的那个子树的节点数,因为只有这一条路(另一个为空,路被截断)。。。。。

而1 2 可以用一个式子搞定,就是返回较大的那个子树的节点数。。。。

而上述就是求最大深度和最小深度的一个差别。。。

代码如下(60 ms)

class Solution {
public:
    int minDepth(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(root==NULL) return 0;
        
        int left = minDepth(root->left);
        int right = minDepth(root->right);
            
        if(left*right==0){
        //左节点或右节点有一个不为空,说明该节点不为叶子。。。返回较大的(叶子节点的那个)
            return left>right?left+1:right+1;
        }
        else{    
            //两个都不为空,返回较小的即可
            return left>right?right+1:left+1;
        }
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值