Poison

111. Minimum Depth of Binary Tree

DFS
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
} else if (root.left == null) {
return minDepth(root.right) + 1;
} else if (root.right == null) {
return minDepth(root.left) + 1;
} else {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
}
BFS
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
class Solution {
public int minDepth(TreeNode root) {
int depth = 0;

Queue<TreeNode> queue = new LinkedList<>();
if (root != null) {
queue.add(root);
}

while (!queue.isEmpty()) {
for (int i = queue.size(); i > 0; i--) {
TreeNode node = queue.poll();
if (node.left == null && node.right == null) {
return depth + 1;
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}

depth++;
}

return depth;
}
}
Reference

111. Minimum Depth of Binary Tree