Trees & Recursion
Tree BFS
🌿
Picture this
Glass tiers of the conservatory light up one level at a time, every plant on a floor before the next floor wakes.
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
level orderby levelshortest depthright side viewzigzagper row
Ask yourself
- Process tree level by level?
- Min depth / level totals / row views?
- Queue, capturing
len(queue)per level.
Canonical template
const q = [root];
for (let head = 0; head < q.length;) {
const levelEnd = q.length;
while (head < levelEnd) {
const node = q[head++];
for (const child of [node.left, node.right]) if (child) q.push(child);
}
}
Common pitfalls
Not snapshotting level size before the inner loop.
Enqueuing
Nonechildren.