zoukankan      html  css  js  c++  java
  • Minimum Depth of Binary Tree,求树的最小深度

    算法分析:递归和非递归两种方法。

    public class MinimumDepthofBinaryTree {
    	
    	//递归,树的最小深度,就是它左右子树的最小深度的最小值+1
    	public int minDepth(TreeNode root) {
            if(root == null)
            {
            	return 0;
            }
            int lmin = minDepth(root.left);
            int rmin = minDepth(root.right);
            if(lmin == 0 && rmin == 0)
            {
            	return 1;
            }
            if(lmin == 0)//左子树为空,右子树不为空,则最小深度为右子子树的最小深度+1
            {
            	return rmin + 1; 
            }
            if(rmin == 0)
            {
            	return lmin + 1;
            }
            return Math.min(lmin, rmin)+1;
        }
    	
    	
    	//非递归,按层遍历,找到第一个叶子结点
    	public int minDepth2(TreeNode root) {
    		if(root == null)
    		{
    			return 0;
    		}
    		ArrayList<TreeNode> list = new ArrayList<>();
    		int count = 1;//初始值为1
    		list.add(root);
    		while(!list.isEmpty())
    		{
    			ArrayList<TreeNode> temp = new ArrayList<>();
    			for (TreeNode node : list) {
    				if(node.left == null && node.right == null)//当节点左右子树都为空时,该节点为第一个叶子节点,该节点的深度即为树的最小深度
    				{
    					return count;
    				}
    				if(node.left != null)
    				{
    					temp.add(node.left);
    				}
    				if(node.right != null)
    				{
    					temp.add(node.right);
    				}
    			}
    			count ++;//按层遍历,每循环一次,就是一层,层数加1
    			list = temp;
    		}
    		return count;
        }
    }
    

      

  • 相关阅读:
    牛客前缀和题、枚举---[HNOI2003]激光炸弹
    牛客贪心题---拼数
    牛客枚举题---明明的随机数
    牛客模拟、差分题---校门外的树
    牛客贪心题---纪念品分组
    03_7_继承和权限控制
    03_6_package和import语句
    03_5_static关键字
    01_8_sql主键生成方式
    01_7_模糊查询实体对象
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5911330.html
Copyright © 2011-2022 走看看