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

    算法分析:求树的最小最大深度时候,都有两种方法,第一种是递归思想。树最大最小深度,即为它的子树的最大最小深度+1,是动态规划的思想。还有一种方法是层序遍历树,只不过求最小深度时,找到第一个叶子节点就可以返回,该节点的深度,即为树的最小深度。求最大深度时,需要层序遍历完整棵树。

    public class MaximumDepthofBinaryTree 
    {
    	public int maxDepth(TreeNode root)
    	{
    		if(root == null)
    		{
    			return 0;
    		}
    		int lmax = maxDepth(root.left);
    		int rmax = maxDepth(root.right);
    		if(lmax == 0 && rmax == 0)
    		{
    			return 1;
    		}
    		if(lmax == 0)
    		{
    			return rmax + 1;
    		}
    		if(rmax == 0)
    		{
    			return lmax + 1;
    		}
    		return Math.max(lmax, rmax) + 1;
    	}
    	
    	public int maxDepth2(TreeNode root)
    	{
    		if(root == null)
    		{
    			return 0;
    		}
    		ArrayList<TreeNode> list = new ArrayList<>();
    		list.add(root);
    		int count = 0;
    		while(!list.isEmpty())
    		{
    			ArrayList<TreeNode> temp = new ArrayList<>();
    			for (TreeNode node : list) {
    				if(node.left != null)
    				{
    					temp.add(node.left);
    				}
    				if(node.right != null)
    				{
    					temp.add(node.right);
    				}
    			}
    			count ++;
    			list = temp;
    		}
    		return count;
    	}
    }
    

      

  • 相关阅读:
    linux常用的基础知识
    【AW346】走廊泼水节
    【AW355】异象石
    【POJ3417】闇の連鎖
    【APIO2010】巡逻
    【SDOI2011】消防
    【BJWC2010】次小生成树
    【POJ3613】Cow Relays
    【POJ1734】Sightseeing trip
    【POJ1094】Sorting it all out
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5911342.html
Copyright © 2011-2022 走看看