Level-order traversal
Visit the tree's nodes level by level, top to bottom and left to right, with a queue; BFS on a tree.
The preorder, inorder and postorder traversals are depth-first: they go to the bottom of a branch first. A level-order traversal visits every node at depth 0, then depth 1, then depth 2, and so on.
Read the full explanation ↓- Time:
O(n) - Space:
O(n) - Horowitz–Sahni, chapter 5
- Johnsonbaugh, chapter 9
The same tree as the depth-first traversals; the output 15, 6, 18, 3, 7, 17, 20 goes level by level.
from collections import dequeclass Node:def __init__(self, key):self.key = keyself.left = Noneself.right = Nonedef level_order(root):out = []if root is None:return outqueue = deque([root])while queue:node = queue.popleft()out.append(node.key)if node.left is not None:queue.append(node.left)if node.right is not None:queue.append(node.right)return out
Start
Local variables
Orange = changed in this step
root object
- key = 15
- left = Node(key=6, left=Node(key=3, left=None, right=None), right=Node(key=7, left=None, right=None))
- right = Node(key=18, left=Node(key=17, left=None, right=None), right=Node(key=20, left=None, right=None))
Call stack
- level_order()line 11
How the work grows with input size
Average of 8 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- visit
- current input (n=7)
Show as a table
| n | visit |
|---|---|
| 3 | 3 |
| 5 | 5 |
| 7 | 7 |
| 9 | 9 |
| 11 | 11 |
| 13 | 13 |
| 15 | 15 |
Explanation
The idea
The preorder, inorder and postorder traversals are depth-first: they go to the bottom of a branch first. A level-order traversal visits every node at depth 0, then depth 1, then depth 2, and so on.
The algorithm
Use a queue (first in, first out):
- Put the root in the queue.
- While the queue is not empty: take the first node, visit it, and add its left and right children to the back.
This is BFS on a graph; since a tree has no cycles, nodes need no "seen" mark.
Cost
Each node enters and leaves the queue once: O(n). The queue grows at most to the size of the widest level.
What to watch in the trace
- Visited nodes are filled in; the queue is in the memory panel.