Input: root = [3, 9, 20, null, null, 15, 7] → Output: 3
The maximum depth is the number of nodes along the longest path from root to the farthest leaf.
TimeO(n)visit each node once
SpaceO(n)queue holds widest level
Visited: 0/5Queue: 0Depth: 0
Processing
In Queue
Processed
Edge highlight
Queue
empty
Depth
0
Ready
Press Play to watch BFS count depth level-by-level, or Step to advance one operation at a time.
Each time we fully process a level, depth += 1.
TimeO(n)visit each node once
SpaceO(h)call stack depth
✎ 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.
═══ MAX DEPTH — BFS ITERATIVE ═══
PATTERN ▸ BFS + level counting O(n) · O(n)
① BASE CASE
if not root: return 0
② INIT
from collections import deque
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 node.left: queue.append(node.left)
if node.right: queue.append(node.right)
⑤ RETURN
return depth
▼ 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.