3.4.3 · D3Trees

Worked examples — Level-order traversal — BFS with queue

2,722 words12 min readBack to topic

This page is the stress-test for level-order BFS. The parent taught the recipe on one friendly tree. Here we deliberately throw every awkward shape at it — empty trees, single nodes, one-sided skews, fat bottom levels — and watch the queue behave correctly in each. If you can hand-trace all of these, no interviewer's tree will surprise you.

Before we begin, one shared vocabulary reminder so no symbol sneaks in undefined:


The scenario matrix

Every tree BFS problem falls into one of these cells. The examples below each carry a tag like (Cell C3) so you can see the coverage is complete.

Cell Case class What's tricky about it Covered by
C1 Empty tree (root is null) Loop must never start; output empty Ex 1
C2 Single node (root only) One dequeue, no children enqueued Ex 2
C3 Balanced / bushy tree Queue swells to width ; grouping matters Ex 3
C4 Left-skewed path Width stays ; degenerate BFS Ex 4
C5 Right-skewed path Same but mirror; test the None-guard on left Ex 4b
C6 Zig-zag / lopsided Levels have different sizes; snapshot test Ex 5
C7 Complete tree, wide bottom Peak queue ; space limit case Ex 6
C8 Word problem (shortest hops) BFS = distance-from-root in disguise Ex 7
C9 Exam twist (right-side view) Use last node of each level snapshot Ex 8

Example 1 — the empty tree (Cell C1)


Example 2 — the single node (Cell C2)


Example 3 — bushy tree, flat AND grouped (Cell C3)

Figure — Level-order traversal — BFS with queue

Example 4 — left-skewed path (Cell C4)

Figure — Level-order traversal — BFS with queue

Example 4b — right-skewed mirror (Cell C5)


Example 5 — lopsided levels (Cell C6)


Example 6 — complete tree, the space limit case (Cell C7)


Example 7 — word problem: fewest hops (Cell C8)


Example 8 — exam twist: right-side view (Cell C9)



Active recall


Connections

  • Parent: Level-order BFS — the recipe these examples stress-test.
  • Breadth-First Search (BFS) — general algorithm; every example is its tree instance.
  • Depth-First Search (DFS) — contrast in Ex 4 and Ex 6 (path order coincidence; stack vs queue space).
  • Queue (FIFO) data structure — the FIFO behavior that keeps every level in order.
  • Stack (LIFO) — what you'd wrongly get with Mistake A.
  • Binary Tree representation — the node/left/right model all traces assume.
  • Shortest path in unweighted graphs — the disguise behind Ex 7.
  • Tree height vs width — why Ex 5's height (3) and width (2) differ, and why Ex 6's do too.