关于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,2],那么,它的最小深度是2,不是1。因为,只有没有任何子节点的节点才叫做叶子节点,虽然根节点没有右子节点,但是它有左子节点,所以它不是叶子节点。而二叉树[1]的最小深度就是1,因为根节点没有任何子节点,所以它既是根节点也是叶子节点,直接计算就可以得到正确结果。

    这道题思路也是比较简单的,我们只需要求出一个节点子节点的最小深度,然后再加上1就是这个节点的最小深度,用递归再合适不过了。直接放已Accepted的代码,如下所示:

    public int minDepth(TreeNode root) {
        if(root==null){
            return 0;
        }else if(root.left!=null && root.right!=null){
            int min_left = minDepth(root.left);
            int min_right = minDepth(root.right);
            return min_left>min_right?min_right+1:min_left+1;
        }else if(root.left!=null){
            return minDepth(root.left)+1;
        }else{
            return minDepth(root.right)+1;
        }
    }


 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值