-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinDepth.java
More file actions
39 lines (38 loc) · 998 Bytes
/
MinDepth.java
File metadata and controls
39 lines (38 loc) · 998 Bytes
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class MinDepth {
public int minDepth(TreeNode root) {
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
if(root == null) return 0;
q.offer(root);
int lvlNums = 1;
int lvl = 1;
while(!q.isEmpty()){
int cnt = 0;
for(int i = 0; i < lvlNums; i++){
TreeNode now = q.poll();
if(now.right == null && now.left == null){
return lvl;
}
if(now.right != null){
q.offer(now.right);
cnt++;
}
if(now.left != null){
q.offer(now.left);
cnt++;
}
}
lvlNums = cnt;
lvl++;
}
return -1;
}
}