-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem111.java
47 lines (41 loc) · 1.19 KB
/
Problem111.java
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
41
42
43
44
45
46
47
import java.util.LinkedList;
import java.util.Queue;
class Problem111 {
public static void main(String[] args) {
Problem111 p = new Problem111();
TreeNode root = new TreeNode(1);
//root.left = new TreeNode(2);
//root.right = new TreeNode(3);
//root.left.right = new TreeNode(4);
System.out.println(p.minDepth(root));
}
public int minDepth(TreeNode root) {
int depth = 0;
if (root == null) {
return depth;
}
if (root.left == null && root.right == null) {
return 1;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int level = 1;
int count = 0;
while(queue.size() > 0) {
count = queue.size();
while(count>0) {
count--;
TreeNode t = queue.poll();
if (t.left == null && t.right == null) return level;
if (t.left != null) {
queue.add(t.left);
}
if (t.right != null) {
queue.add(t.right);
}
}
level++;
}
return 0;
}
}