Input: root = [3, 9, 20, null, null, 15, 7] → Output: 2
The minimum depth is the shortest path from root to the nearest leaf node. BFS guarantees the first leaf found is the shallowest.
TimeO(n)worst-case visits all nodes
SpaceO(n)queue holds widest level
Visited: 0/5Queue: 0Depth: 0
Processing
In Queue
Processed
Leaf Found!
Edge highlight
Queue
empty
Depth
0
Ready
Press Play to watch BFS find the shallowest leaf, or Step to advance one operation at a time.
Unlike max depth, BFS returns immediately when it hits the first leaf — no need to traverse the entire tree.
TimeO(n)visit each node once
SpaceO(h)call stack depth
Key Insight
A node with one child is not a leaf. The minimum depth is the shortest path to a leaf node (node with no children). If a node has only one child, that path must continue—you can't stop there.
✎ Whiteboard
3
⌨ Type It — Build Muscle Memory
Practice until you don't need to look. Use the guide comments below as scaffolding. Type the full implementation in the editor. The green highlights are the nuances to burn into memory.
═══ MIN DEPTH — BFS ITERATIVE ═══
PATTERN ▸ BFS + early exit at first leaf O(n) · O(n)
① BASE CASE
if not root: return 0
② INIT
queue = deque([root])
depth = 0
③ BFS LOOP
while queue:
level_size = len(queue)
depth += 1
④ PROCESS LEVEL
for i in range(level_size):
node = queue.popleft()
if not node.left and not node.right: return depth
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
▼ your implementation ▼
Verify your solution:
⌨ Type It — Recursive DFS
Practice until you don't need to look. The green highlights are the nuances to burn into memory.