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

  

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-04
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2021-09-03
  • 2021-06-26
猜你喜欢
  • 2021-12-16
  • 2021-07-20
  • 2021-11-12
  • 2022-12-23
  • 2021-09-12
  • 2021-08-11
  • 2021-11-10
相关资源
相似解决方案