-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinDepthOfBT.java
More file actions
30 lines (29 loc) · 879 Bytes
/
MinDepthOfBT.java
File metadata and controls
30 lines (29 loc) · 879 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
import java.util.ArrayDeque;
public class MinDepthOfBT {
public int minDepth(TreeNode root) {
if (root == null)
return 0;
ArrayDeque<TreeNode> queue = new ArrayDeque<TreeNode>();
// corresponding depth of each node
ArrayDeque<Integer> depths = new ArrayDeque<Integer>();
queue.addLast(root);
depths.addLast(1);
int d = -1;
while (true) {
TreeNode n = queue.removeFirst();
d = depths.removeFirst();
if (n.left == null && n.right == null) {
break;
}
if (n.left != null) {
queue.addLast(n.left);
depths.addLast(d+1);
}
if (n.right != null) {
queue.addLast(n.right);
depths.addLast(d+1);
}
}
return d;
}
}