首页 > 代码库 > [LeetCode][Java] Minimum Depth of Binary Tree

[LeetCode][Java] Minimum Depth of Binary Tree

题目:

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