Level order with a queue
After this: Follow a walk that uses a queue instead of the call stack.
On this page · 10 sections · 3 checks
The three walks so far go as deep as they can before they come back. Preorder on the example tree goes 1, 2, 4 before it ever reaches 3. But sometimes you want to read a tree the way you read a page: the top row, then the next row, and so on. How can a program do that?
Row by row
Each row of the drawing is called a level. The nodes on a level all have the same depth.
| Level | Nodes, left to right |
|---|---|
| 0 | 1 |
| 1 | 2, 3 |
| 2 | 4, 5, 6 |
Reading the rows in turn gives 1 2 3 4 5 6. This order is called , or breadth-first.
You can read it from the drawing with your eyes. A program cannot. It holds only the root, and each node knows only its own children. After visiting 2, the program must go to 3, but node 2 has no link to node 3. So the program has to remember which nodes it has seen but not yet visited.
A queue of waiting nodes
The tool for this is a from the stacks and queues tutorial. Think of people waiting in a line at a shop. New people join at the back, and the next person served is at the front. This is called first in, first out.
Two words go with a queue: adding at the back is called enqueue, and taking from the front is called dequeue.
Here is the method. There is no recursion this time.
- Put the root in the queue.
- Take the node at the front of the queue, and visit it.
- Put its children at the back of the queue, left child first.
- Go back to step 2. Stop when the queue is empty.
The smallest example
Here it is on the three-node tree.
| Step | Take from the front and visit | Add to the back | Queue afterwards |
|---|---|---|---|
| Start | 1 | 1 | |
| 1 | 1 | 2, 3 | 2, 3 |
| 2 | 2 | 3 | |
| 3 | 3 | (empty) |
The visited order is 1 2 3, and the queue is empty, so the walk stops.
The example tree
Now the same table for the six-node tree. Follow it with your finger, one row at a time.
| Step | Take from the front and visit | Add to the back | Queue afterwards |
|---|---|---|---|
| Start | 1 | 1 | |
| 1 | 1 | 2, 3 | 2, 3 |
| 2 | 2 | 4, 5 | 3, 4, 5 |
| 3 | 3 | 6 | 4, 5, 6 |
| 4 | 4 | 5, 6 | |
| 5 | 5 | 6 | |
| 6 | 6 | (empty) |
The visited order is 1 2 3 4 5 6, the same as reading the rows.
Look at step 2. Node 3 is at the front of the queue, ahead of 4 and 5. That is how the program gets from 2 to 3: node 3 was waiting in the queue.
The code
from collections import deque
def level_order(root): out = [] if root is None: return out queue = deque([root]) while queue: node = queue.popleft() # the front of the queue out.append(node.value) # visit if node.left: queue.append(node.left) # children join at the back if node.right: queue.append(node.right) return outstatic List<Integer> levelOrder(Node root) { List<Integer> out = new ArrayList<>(); if (root == null) return out; Deque<Node> queue = new ArrayDeque<>(); queue.offer(root); while (!queue.isEmpty()) { Node node = queue.poll(); // the front of the queue out.add(node.value); // visit if (node.left != null) queue.offer(node.left); // children join at the back if (node.right != null) queue.offer(node.right); } return out;}Here is how to read it.
outis the list of visited values. If the tree is empty, the function returns it straight away.- The queue starts with the root in it.
- The loop runs until the queue is empty. Each time round, it takes the node at the front and adds its value to
out. - The two
iflines add the node's children at the back, left first. A missing child is not added.
print(level_order(root))[1, 2, 3, 4, 5, 6]
System.out.println(levelOrder(root));[1, 2, 3, 4, 5, 6]
Each node joins the queue once and leaves once, so the cost is O(n): the work grows at the same rate as the number of nodes.
Why a queue gives levels
The reason is first in, first out. Follow it on the example tree.
- Nodes 2 and 3, at depth 1, join the queue when the root leaves it.
- Nodes at depth 2 join only when a depth 1 node leaves. So they always join behind any depth 1 node that is still waiting.
- A queue never lets a node go ahead of one that joined earlier. So every depth 1 node comes out before any depth 2 node.
The same is true at every depth, so the levels never mix.
What if we use a stack?
A takes the newest item first. Swap the queue for a stack, change nothing else, and the same code gives 1 3 6 2 5 4. After node 1, the stack holds 2 and 3. The newest is 3, so 3 comes next, and the walk goes down the right side before it comes back for 2.
So a stack goes deep, and a queue goes across. The graphs tutorial uses this same swap to get its two searches.
Watch it happen
There is no Stack band here. The Queue band shows the nodes that are waiting. Before the run, the task asks which node is visited fourth. Tap your answer in the picture, and then watch the queue.
- Level orderRun Level order. There is no Stack band this time, so watch the Queue band. After 2 is taken from the front, the queue holds 3, 4, 5.
Run an operation to begin.
Check yourself
Here is a larger tree, drawn below. What does level order give?
Level order on the example tree has taken 2 from the front, visited it, and added its children. What is in the queue, from front to back?
Why does using a queue give one level at a time?
Connect
- Follow level order: take a node from the front of the queue, visit it, add its children at the back, and stop when the queue is empty.
- Say what is in the queue at any point of the walk.
- Explain why a queue gives one level at a time, and what a stack would give instead.