Sub topic 9
Level-order traversal with a queue
This chapter assumes you know the Node class from earlier, how a queue works (first in, first out), and Big-O basics. Level-order traversal is also called breadth-first traversal. It visits every node at depth 0, then every node at depth 1, and so on, moving left to right within each level.
Why a queue
Depth-first traversals use the call stack, which goes deep before going wide. Level-order needs the opposite behavior: nodes discovered earlier must be visited earlier. That is first in, first out, so a queue fits.
The algorithm:
- Put the root in the queue.
- Remove the node at the front and visit it.
- Add its left child, then its right child, to the back, skipping missing children.
- Repeat until the queue is empty.
Separating the levels
The code below returns a list of lists, one per level. At the start of each pass of the while loop, the queue holds exactly the nodes of one level. Reading len(queue) at that moment fixes how many nodes belong to the level. The inner loop processes that many nodes, and the children it appends form the next level.
from collections import deque
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def level_order(root):
if root is None:
return []
result = []
queue = deque([root])
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.value)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
result.append(level)
return result
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
print(level_order(root)) # [[1], [2, 3], [4, 5]]Tracing the queue on the example tree:
| Pass | Queue at start | Visited | Level recorded |
|---|---|---|---|
| 1 | 1 | 1 | [1] |
| 2 | 2, 3 | 2, 3 | [2, 3] |
| 3 | 4, 5 | 4, 5 | [4, 5] |
If you only need a flat list, drop the inner for loop and append each value to one list.
Cost
Every node enters and leaves the queue once, so time is O(n). Space depends on the widest level. A perfect tree has about n/2 nodes in its last level, so the queue reaches O(n). A degenerate tree (a chain) never holds more than one node, so the queue stays at O(1). This is the reverse of recursive depth-first traversal, whose stack grows with height.
Common errors
- Using a list with
pop(0). It shifts every remaining element, so each removal costs O(n). Usecollections.dequeandpopleft(). - Reading
len(queue)inside the loop condition. The queue grows while you work, so the level boundary moves. Evaluaterange(len(queue))once per pass, as above. - Forgetting the empty-tree check.
deque([None])would makenode.valuefail onNone. - Enqueuing
Nonechildren. Check each child before appending it.
Exercise
Change level_order so it returns the largest value on each level. For the example tree, what should it return, and which single line changes?
Show answer
It should return [1, 3, 5]. Replace result.append(level) with result.append(max(level)). The queue logic stays the same because level already holds the values of one level.