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.

solution:

采用BFS的方式遍历tree即可。 同时为了知道是在哪一层 加入一个每一层结束的signal node。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int minDepth(TreeNode root) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         if(root == null) return 0;
15         LinkedList<TreeNode> q = new LinkedList<TreeNode>();
16         q.add(root);
17         q.add(new TreeNode(-999));//一个singal,可以用 INT_MAX 代替比较好。
18         int num = 0;
19         while(q.size() != 0){
20             TreeNode tn = q.remove();
21             if(tn.val == - 999){
22                 num ++;
23                 q.add(new TreeNode(-999));
24             } 
25             else{
26                 if(tn.left != null) q.add(tn.left);
27                 if(tn.right != null) q.add(tn.right);
28                 if(tn.left == null && tn.right == null){
29                     return num + 1;
30                 }
31             }
32             
33         }
34         return num + 1;//这句永远都跑不到
35     }
36 }

 

posted on 2013-09-12 13:47  Step-BY-Step  阅读(169)  评论(0编辑  收藏  举报

导航