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.
| Variant | Change |
|---|---|
| zigzag | write every other level reversed |
| reverse level order | collect levels, output them last to first |
| maximum width | store each node's position: children of p are 2p and 2p + 1 |
| anagram levels | compare 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
- Binary Tree Level Order Traversalmediumguide ready
- Binary Tree Zigzag Level Order Traversalmediumguide ready
- Maximum Width of Binary Treemediumguide ready
- All Nodes Distance K in Binary Treemediumguide ready
- Minimum time taken to burn the BT from a given Nodemediumguide ready
- Reverse Level Order traversalmediumguide ready
- Check if all levels of two trees are anagrams or notmediumguide ready