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

  

posted @ 2016-09-27 02:04  32ddd  阅读(534)  评论(0编辑  收藏  举报