111 Minimum Depth of Binary Tree

111. Minimum Depth of Binary Tree

1. Question

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

2. Implementation

(1) DFS recursion
1
class Solution {
2
public int minDepth(TreeNode root) {
3
if (root == null) return 0;
4
if (root.left == null) return 1 + minDepth(root.right);
5
if (root.right == null) return 1 + minDepth(root.left);
6
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
7
}
8
}
Copied!
(2) BFS
1
class Solution {
2
public int minDepth(TreeNode root) {
3
if (root == null) {
4
return 0;
5
}
6
7
Queue<TreeNode> queue = new LinkedList<>();
8
queue.add(root);
9
int depth = 0;
10
11
while (!queue.isEmpty()) {
12
int size = queue.size();
13
++depth;
14
15
for (int i = 0; i < size; i++) {
16
TreeNode curNode = queue.remove();
17
18
if (curNode.left == null && curNode.right == null) {
19
return depth;
20
}
21
22
if (curNode.left != null) {
23
queue.add(curNode.left);
24
}
25
26
if (curNode.right != null) {
27
queue.add(curNode.right);
28
}
29
}
30
}
31
return depth;
32
}
33
}
Copied!

3. Time & Space Complexity

DFS recursion: 时间复杂度: O(h), 空间复杂度: O(h)
BFS:时间复杂度O(n), 空间复杂度: O(w), w为树一层中有最多node的个数