Learn / Trees

Level order BFS

Breadth-first search visits a tree level by level with a queue. Taking exactly the current queue size each round separates the levels, which gives zigzag order, widths and per-level checks. Adding parent links turns the tree into a graph, so BFS can spread outwards from any node, as in distance-k and burning-tree problems.

How to recognise it

  • The answer is grouped by level or depth.
  • Something spreads from a node one step per unit of time.
  • You need the nearest, shallowest or widest part of the tree.

The level loop

queue = [root]
while queue:
    size = len(queue)               # this level
    repeat size times:
        node = pop front; record node
        push its children

What a node, a child, a leaf and a level are is on the Structures page.

VariantChange
zigzagwrite every other level reversed
reverse level ordercollect levels, output them last to first
maximum widthstore each node's position: children of p are 2p and 2p + 1
anagram levelscompare each level's values after sorting

BFS from any node

Record each node's parent first. Then a node's neighbours are its two children and its parent, and BFS from the start node reaches everything at distance 1, then 2, and so on. Keep a visited set so you never walk back.

Common mistakes

  • Reading queue.size() inside the loop condition while the queue is growing.
  • Forgetting the visited set when walking upwards and downwards.

Problems

0 of 7 solved

Check yourself

Level order of the tree 1 (2 (4, 5), 3 (6, 7))?

How do you know where one level ends in the queue?

Why add parent links for 'all nodes at distance k'?

In Maximum Width, why are positions shifted at each level?