码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java] Minimum Depth of Binary Tree

时间:2015-07-21 10:39:59      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   minimum depth of bin   

题目:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

题意:

给定一棵二叉树,返回它的最小高度。

最小高度是指从根节点到最近的叶子节点的最短路径中的节点的数目。

算法分析:

  * 借助堆

  * 类似《Binary Tree Level Order Traversal》中的算法

  * 出现下一层无自带的情况,立即退出,返回该层的层数

AC代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution 
{
   public int minDepth(TreeNode root) 
    {
		int index=0;
		boolean flag=false;
		ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
		ArrayList<Integer> list= new ArrayList<Integer>();
    	LinkedList<TreeNode> que = new LinkedList<TreeNode>(); 
		
		if (root==null) return 0;
    	que.add(root);
    	while(que!=null)
    	{
    		TreeNode tem;
    		int size=que.size();
    		list.clear();
    		for(int i=0;i<size;i++)
    		{
	    		tem=que.poll();
	    		list.add(tem.val);
	    		if(tem.left==null&&tem.right==null)
	    		{
	    			flag=true;//只要出现父节点无子节点的情况,就直接跳出,统计size
	    			break;
	    		}
	    		if(tem.left!=null) que.add(tem.left);
	    		if(tem.right!=null) que.add(tem.right);
    		}
    		res.add(new ArrayList<Integer>(list));
    		if(flag) return res.size();
    		else index=res.size();
    	}
    	
    	return index;    
    }
}

版权声明:本文为博主原创文章,转载注明出处

[LeetCode][Java] Minimum Depth of Binary Tree

标签:leetcode   java   minimum depth of bin   

原文地址:http://blog.csdn.net/evan123mg/article/details/46981461

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