-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minimum Depth of Binary Tree
40 lines (39 loc) · 1.16 KB
/
Minimum Depth of Binary Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == null) return 0;
int result = 1;
Queue<TreeNode> temp = new LinkedList<TreeNode>();
temp.add(root);
return helpler(temp, result);
}
private int helpler(Queue<TreeNode> temp, int result)
{
if(temp.isEmpty())
return result;
int all = temp.size();
for(int i=0; i<all; i++)//search all the elements in the Queue
{
TreeNode current = temp.poll();
if(current.left == null && current.right == null)
return result;
else{
if(current.left != null)
temp.add(current.left);
if(current.right != null)
temp.add(current.right);
}
}//end while loop
result++;
return helpler(temp, result);
}
}