Minimum Depth of Binary Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #111
Given a binary tree, return its minimum depth: the number of nodes on the shortest path from the root down to the nearest leaf.
Examples
text
[3,9,20,null,null,15,7] → 2
[2,null,3,null,4,null,5,null,6] → 5 (a skewed chain: the only leaf is 6)Hints
- Careful:
1 + min(left, right)is wrong when one child is missing, because a null child is not a leaf. - BFS visits nodes level by level. The first leaf you see is at the minimum depth.
Approach
BFS (best): process level by level and return the depth of the first leaf. This can finish long before visiting the whole tree.
DFS: if one child is null, you must go through the other one:
text
if not left: return 1 + minDepth(right)
if not right: return 1 + minDepth(left)
return 1 + min(minDepth(left), minDepth(right))Complexity
Time: O(n). Space: O(w), the tree's maximum width.
Python solution
from collections import deque
def minDepth(root):
if not root:
return 0
q = deque([(root, 1)])
while q:
node, d = q.popleft()
if not node.left and not node.right:
return d
if node.left:
q.append((node.left, d + 1))
if node.right:
q.append((node.right, d + 1))JavaScript solution
function minDepth(root) {
if (!root) return 0;
let level = [root], d = 1;
while (level.length) {
const next = [];
for (const n of level) {
if (!n.left && !n.right) return d;
if (n.left) next.push(n.left);
if (n.right) next.push(n.right);
}
level = next; d++;
}
return d;
}