forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminidepthofbinarytree.java
More file actions
executable file
·37 lines (37 loc) · 1.04 KB
/
minidepthofbinarytree.java
File metadata and controls
executable file
·37 lines (37 loc) · 1.04 KB
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
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null){
return 0;
}
Queue<TreeNode> now = new LinkedList<TreeNode>();
Queue<TreeNode> next = new LinkedList<TreeNode>();
int layer = 0;
now.offer(root);
while(!now.isEmpty() || !next.isEmpty()){
while(!now.isEmpty()){
TreeNode tn = now.poll();
if(tn.left!=null) next.offer(tn.left);
if(tn.right!=null) next.offer(tn.right);
if(tn.left==null && tn.right==null) return layer+1;
}
if(!next.isEmpty()){
Queue<TreeNode> tmp = now;
now = next;
next = tmp;
}
layer++;
}
return layer;
}
}