-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
82 lines (70 loc) · 1.94 KB
/
Solution.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.ArrayDeque;
import java.util.Queue;
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> q = new ArrayDeque<>();
q.offer(root);
int depth = 0;
while (!q.isEmpty()) {
int breadth = q.size();
depth++;
for (int i = 0; i < breadth; i++) {
TreeNode node = q.poll();
if (node.left == null && node.right == null) {
return depth;
}
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
}
}
return depth;
}
public static void main(String[] args) {
Solution s = new Solution();
// 1
TreeNode a = new TreeNode(3,
new TreeNode(9),
new TreeNode(20,
new TreeNode(15),
new TreeNode(7)
)
);
System.out.println(s.minDepth(a));
assert s.minDepth(a) == 2;
// 2
TreeNode b = new TreeNode(2,
null,
new TreeNode(3,
null,
new TreeNode(4,
null,
new TreeNode(5,
null,
new TreeNode(6)
)
)
)
);
System.out.println(s.minDepth(b));
assert s.minDepth(b) == 5;
// 3
TreeNode c = new TreeNode(2);
assert s.minDepth(c) == 1;
// 4
assert s.minDepth(null) == 0;
// 5
TreeNode d = new TreeNode(1,
new TreeNode(2,
new TreeNode(4),
new TreeNode(5)
),
new TreeNode(3)
);
assert s.minDepth(d) == 2;
}
}