【JAVA】【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.

思路:

两种方法:
第一,使用递归,相当于遍历了整个二叉树,递归返回深度浅的那棵子树的深度。
第二,按层检查有没有叶子节点,有的话停止检查,返回当前层数。至于实现这个按层检查,可以用递归的方法。该法不用遍历整个树。
                                                          --来自于 牛客426550号
由于我本人只想到第一种办法,看到牛客友人 牛客426550号给的思路觉得考虑的比较周全,所以就在此引用一下。谢谢!
递归要分清楚几种情况:
1、当根节点为空时,返回0
2、当只有左子节点(无右子节点)时,返回 1
3、当只有右子节点(无左子节点)时,返回 1
4、当左右子节点都存在时,分别计算左子树和右子树的深度,min(左子树最小深度,右子树最小深度)+1
public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

public class Solution {
  public int run(TreeNode root) {          
        if(root!=null){
            int left = Integer.MAX_VALUE;
            int right = Integer.MAX_VALUE;
            if(root.left!=null){
                left = run(root.left);
            }
            if(root.right!=null){
                right = run(root.right);
            }
            if(left<right){
                return left+1;
            }
            else if(left>right){
                return right+1;
            }
            else if(left==right&&left!=Integer.MAX_VALUE){
                return left+1;
            }
            else 
                return 1;
        }
        return 0;
            
        
    
    }  
}

 当然,还有一个较简洁的递归方法,最核心的思想就是根节点到达最近的叶子节点的路径长度:

1、当根为空时,输出0

2、当左子树为空时,输出右子树深度+1

3、当右子树为空时,输出左子树深度+1

4、以上条件都不满足时,输出min(左子树深度,右子树深度)+1

public class Solution {
    public int run(TreeNode root) {
        if(root==null) 
            return 0;
        if(root.left==null) 
            return run(root.right)+1;
        if(root.right==null)
            return run(root.left)+1;
        return Math.min(run(root.left),run(root.right))+1;
            
    }
}
View Code

 

转载于:https://www.cnblogs.com/weimiaomiao/p/5844165.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值