• 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;
    	}
    }
    

      

  • 相关阅读:
    可扩容分布式session方案
    Linux 极限压缩
    python调用jenkinsAPI
    Jenkins-slave分布式跨网络发布
    mysql查看指定数据库各表容量大小
    FastAPI--依赖注入之Depends(8)
    FastAPI--跨域处理(7)
    FastAPI--中间件(6)
    FastAPI--错误处理(5)
    FastAPI--响应报文(4)
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5911342.html
Copyright © 2020-2023  润新知