Minimum Depth of Binary Tree
Find the length of the shortest path from the root to any leaf.
Open on LeetCode ↗Intuition
Mirroring maxDepth with min(depth(left), depth(right)) looks natural but breaks the moment a node has only ONE child: the missing side reports depth 0, and min() happily returns 0, claiming a leaf exists where there is none. A leaf is a node with NO children at all -- when only one child is present you must recurse into that side exclusively and ignore the missing one. BFS sidesteps the whole trap: walking level by level, the very first leaf you dequeue is guaranteed to be at the minimum depth, since BFS never explores a deeper level before a shallower one is exhausted.
BFS returns on the first leaf it meets, which is by construction the shallowest — so the search stops early instead of exploring the whole tree. This is the case where BFS strictly beats DFS, since DFS must visit every node before it can be sure.
Approach
BFS level by level
Seed a queue with the root at depth 1. Process nodes in FIFO order, tracking each node's depth alongside it.
Stop at the first true leaf
The instant a dequeued node has no left AND no right child, its depth is the answer -- return immediately, no need to drain the rest of the queue.
Otherwise keep expanding
Push any existing children with depth + 1 and continue; a node with only one child is not a leaf and must not be mistaken for one.
Solution & live demo
Common pitfalls
Using the max-depth recurrence with min
return 1 + min(minDepth(root.left), minDepth(root.right))
if not node.left and not node.right:
return depthFor a node with one child, the missing side returns 0 and min picks it — reporting a depth that ends at a non-leaf. The recursive version needs an explicit single-child case; BFS sidesteps it entirely.
Returning at the first node with a missing child
if not node.left or not node.right:
return depthif not node.left and not node.right:
A node with exactly one child is internal, not a leaf. The or version stops at the first such node and reports a depth shorter than any real root-to-leaf path.
Using DFS and scanning every path
# full DFS, tracking the minimum leaf depth
queue = deque([(root, 1)])
Correct but visits every node even when a leaf sits one level down. BFS reaches the shallowest leaf first and returns immediately, which on a deep skewed tree is the difference between O(1) and O(n).
Edge cases
Return 0 immediately, no nodes to search.
Root is dequeued first and has no children -- min depth 1.
BFS still finds the single leaf at the true bottom; a min()-based DFS would wrongly report 1.
First level with any leaf ends the search, often well before reaching every node.