码迷,mamicode.com
首页 > 其他好文 > 详细

Maximum Depth of Binary Tree,求树的最大深度

时间:2016-09-27 06:57:43      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

算法分析:求树的最小最大深度时候,都有两种方法,第一种是递归思想。树最大最小深度,即为它的子树的最大最小深度+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 = 1;
		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;
	}
}

  

Maximum Depth of Binary Tree,求树的最大深度

标签:

原文地址:http://www.cnblogs.com/masterlibin/p/5911342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!