Home/Data structures & algorithms/Binary trees and level-order traversal

Binary trees and level-order traversal

Use a queue to visit nodes by depth

A tournament viewer stores the final match at the root of a binary bracket, with earlier matches underneath it. The display needs the final first, then its semifinals together, then the next round. Following one branch to the bottom would mix those rows.

Level-order traversal keeps the next row in a queue. The match labels don't need sorting; their left-to-right order comes from the bracket itself.

Displaying a bracket one round at a time

Breadth-first traversal visits one depth before the next. A queue preserves left-to-right discovery if children are enqueued left then right. A stack instead follows depth-first order.

Keeping children in the next frontier

With root a, children b, c, and d beneath b, the rows are [a], [b, c], and [d]. Snapshot the queue length before processing a row. When processing b adds d, that new child must wait for the next row rather than extend the current one. A missing child contributes no placeholder label.

go
root := &Tree{Name: "root", Left: &Tree{Name: "left"}}
fmt.Println(root.Left.Name)

A wide bracket needs queue space

Capture the current frontier size before adding children or next-level nodes can leak into the current row. A slice queue with an advancing head avoids repeated copying, but consumed pointers may retain memory; clearing slots or rotating frontier buffers prevents unnecessary retention. Use level order for breadth reports and shortest unweighted-tree depths; recursion is often simpler for subtree summaries.

A queue traversal visits each of n nodes once. Its working frontier uses O(w) space for maximum width w, while returned rows contain O(n) labels. Rewalking from the root for every depth can become O(n²) on a chain. Depth-first traversal may suit subtree computations better.

The bracket stores a tree; a shared or cyclic match graph would also need discovery tracking.

Practice Binary trees and level-order traversal

Implement the exercise in a full-screen workspace, then run its tests.

Open practice
Next lessonBinary search trees