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

Minimum Depth of Binary Tree,求树的最小深度

时间:2016-09-27 01:48:39      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

算法分析:递归和非递归两种方法。

public class MinimumDepthofBinaryTree {
	
	//递归,树的最小深度,就是它左右子树的最小深度的最小值+1
	public int minDepth(TreeNode root) {
        if(root == null)
        {
        	return 0;
        }
        int lmin = minDepth(root.left);
        int rmin = minDepth(root.right);
        if(lmin == 0 && rmin == 0)
        {
        	return 1;
        }
        if(lmin == 0)//左子树为空,右子树不为空,则最小深度为右子子树的最小深度+1
        {
        	return rmin + 1; 
        }
        if(rmin == 0)
        {
        	return lmin + 1;
        }
        return Math.min(lmin, rmin)+1;
    }
	
	
	//非递归,按层遍历
	public int minDepth2(TreeNode root) {
		if(root == null)
		{
			return 0;
		}
		ArrayList<TreeNode> list = new ArrayList<>();
		int count = 1;
		list.add(root);
		while(!list.isEmpty())
		{
			ArrayList<TreeNode> temp = new ArrayList<>();
			for (TreeNode node : list) {
				if(node.left == null && node.right == null)//当节点左右子树都为空时,该节点的深度即为树的最小深度
				{
					return count;
				}
				if(node.left != null)
				{
					temp.add(node.left);
				}
				if(node.right != null)
				{
					temp.add(node.right);
				}
			}
			count ++;//按层遍历,每循环一次,就是一层,层数加1
			list = temp;
		}
		return count;
    }
}

  

Minimum Depth of Binary Tree,求树的最小深度

标签:

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

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