Walk a tree level by level with a queue to get averages, right-side views, zigzags, widths and column views.
You are building the page that shows a comment thread. Every comment has at most two direct replies, a left one and a right one, and the page loads one row at a time. First the top comment, then its replies, then the replies to those.
Your team lead asks for three views of the same thread:
All three read the tree one level at a time.
At a station, a guard lets people through a gate in rounds. When the bell rings, the guard counts the people in the line at that moment, and lets exactly that many through. Anyone who joins the line during the round waits for the next bell.
Here is how this maps to a tree. The line is a queue, and the count at the bell is the size of the queue at the start of a round. Each person who goes through brings up to two friends, who join the back of the line. They are the next level.
A ticket gate lets through exactly the people in the line when the bell rings. People who join during the round wait: they are the next level.
A level is all the nodes at the same depth. Depth counts links from the root, as before, so the root has depth 0. Levels are counted from 1: level 1 is the root, level 2 holds its children, and in general a node at depth d is on level d + 1.
A queue is a line: you take from the front and add at the back, so the first item added is the first taken. That is called first in, first out. Because of it, a queue visits a tree level by level. Every node of one level is taken before any node of the next level, and each level comes out from left to right.
The new idea in this lesson is one number. Where does one level end and the next begin? The children join the same queue, so the queue does not say. The answer is to count the queue at the start of each round.
Step by step: A tree in memory. The animated player loads in your browser.
Predict what happens
Q A queue holds 3 and 10. You take 3 and add its children 1 and 6, and then take 10 and add its child 14. What does the queue hold next, from front to back?
Answer: B
A queue is first in, first out. The children of 3 were added before the child of 10, and 1 was added before 6. So the order is 1, 6, 14.
We use one tree for most of the examples. The numbers are only ids.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13Keep a queue. At the start of each round, write down its size. Take that many nodes from the front. Add each one's children at the back, left before right.
from collections import deque
def levels(root):
rows = []
if root is None:
return rows
queue = deque([root])
while queue:
size = len(queue)
row = []
for _ in range(size):
node = queue.popleft()
row.append(node.value)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
rows.append(row)
return rowsTrace it on the tree above. The queue is written from the front to the back.
| Round | Queue at the start | size |
Row | Queue at the end |
|---|---|---|---|---|
| 1 | 8 | 1 | 8 | 3, 10 |
| 2 | 3, 10 | 2 | 3, 10 | 1, 6, 14 |
| 3 | 1, 6, 14 | 3 | 1, 6, 14 | 4, 7, 13 |
| 4 | 4, 7, 13 | 3 | 4, 7, 13 | empty |
The answer is [[8], [3, 10], [1, 6, 14], [4, 7, 13]]. Each node was added once and taken once, so the walk takes n steps.
A level-order walk takes a node from the front of a queue and adds its children at the back. Each round takes exactly the nodes that were waiting.
Step by step: A level-order walk. The animated player loads in your browser.
Exercise · Put it in order: The size of every round. A tree is kept as two lists: node 0 is the root, and left[i] and right[i] are the children of node i, or -1 for none. Arrange the lines into a function that returns how many nodes each level holds, from the top down, using a queue and a snapshot of its size at the start of each round.
def level_sizes(left, right):
sizes = []
queue = [0] if left else []
head = 0
while head < len(queue):
sizes.append(len(queue) - head)
end = len(queue)
while head < end:
node = queue[head]
head += 1
queue += [c for c in (left[node], right[node]) if c != -1]
return sizes
sizes.append(len(queue))During round 2, the queue holds 3 and 10 at the start. After taking 3 it holds 10, 1 and 6, and after taking 10 it holds 1, 6 and 14. If you used the length of the queue to decide when the round ends, it would never be 2: the children keep arriving.
So the size is a snapshot, taken before any child is added. Write it down once, and loop that many times.
Predict what happens
Q In round 3 of the walk above, the queue holds 1, 6 and 14 at the start. What does size hold, and what is the queue at the end of the round?
Answer: B
The size is 3, taken before any child is added. Node 1 adds nothing, 6 adds 4 and 7, and 14 adds 13. The three nodes of the round are gone, so the queue holds 4, 7, 13.
Most questions in this lesson run the same rounds, and keep a different summary of each row.
total // size. On the tree above the totals are 8, 13, 21 and 24, so the answer is [8, 6, 7, 8].[8, 10, 14, 13].[8, 10, 14, 13].The level 2 average is 6.5, rounded down to 6. A level of 30,000 comments with a million reactions each can pass 3 x 10^10, so Java and C++ need a 64-bit total.
On this tree the largest and the last of each level are the same, because it is a search tree. They are different in general. A root 4 with the children 9 and 2 has the largest 9 and the last 2 on level 2.
For each level, you see the node that is furthest to the right. In the round, that is the node at position size - 1.
It is tempting to follow only right children: 8, then 10, then 14. That gives [8, 10, 14] and misses 13. Node 13 is the left child of 14, but on level 4 nothing is to its right, so it is the one you see.
The view from the right is the last node taken in each round. It can be a left child, so following only right children misses it.
Exercise · Break it: Find the tree this view gets wrong. This function returns the view from the right edge of a tree by following right children from the root. Find a tree where it gives the wrong view. The tree is a list in level order, left to right, row by row, where -1 means "no node" (every real id is positive).
def right_view(root):
view = []
node = root
while node:
view.append(node.value)
node = node.right
return viewPredict what happens
Q A level holds the values 4, 9 and 2, from left to right. What are the view from the right and the largest value of this level?
Answer: C
The view from the right is the last node of the level, which is 2. The largest value is 9. They are the same only when the last node happens to be the largest.
A zigzag reads level 1 from left to right, level 2 from right to left, level 3 from left to right again, and so on. On the tree above it is [[8], [10, 3], [1, 6, 14], [13, 7, 4]].
Do not change the order of the queue. The queue must give every level from left to right, so that the children of the next level come out in the right order. Change only where each value is written.
Number the rows written so far from 0, so level 1 is row 0. On an even row, the node at position i of the round goes in slot i. On an odd row it goes in slot size - 1 - i, so the first node taken lands at the far right.
Exercise · Find the bug: The slot that falls off the row. This zigzag keeps the queue in normal left-to-right order and only changes where each value is written: on an odd row, from the far right. It crashes or writes in the wrong place. Which line is wrong?
from collections import deque
def zigzag(root):
rows = []
if root is None:
return rows
queue = deque([root])
while queue:
size = len(queue)
row = [0] * size
for i in range(size):
node = queue.popleft()
slot = i if len(rows) % 2 == 0 else size - i
row[slot] = node.value
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
rows.append(row)
return rowsPredict what happens
Q To make a zigzag, a program adds the right child before the left child whenever the row number is odd. What goes wrong?
Answer: B
The order of a level in the queue decides the order of the children that follow. Changing the order of adding children on some rows reorders later levels, and from the third level the rows are wrong.
The width of a level counts the empty slots between its leftmost and rightmost nodes, as if the tree were drawn as a full tree. On the tree above, level 3 holds 1, 6 and 14. Node 10 has no left child, so a slot is empty between 6 and 14.
Give each node a position. A node at position p has its left child at 2p and its right child at 2p + 1. The width of a level is the last position minus the first, plus one.
| Level | Nodes (positions) | First position | Width |
|---|---|---|---|
| 1 | 8 (0) | 0 | 1 |
| 2 | 3 (0), 10 (1) | 0 | 2 |
| 3 | 1 (0), 6 (1), 14 (3) | 0 | 4 |
| 4 | 4 (2), 7 (3), 13 (6) | 2 | 5 |
Level 3 has 3 nodes and a width of 4. Level 4 has 3 nodes and a width of 5, which is the largest.
The width of a level counts the empty slots between its leftmost and rightmost nodes. Give nodes positions, and subtract the first position of each level.
Exercise · Predict the output: How wide is the widest level?. A tree has the root 1. Its left child 2 has a left child 4, and 4 has a left child 8. Its right child 3 has a right child 7, and 7 has a right child 14. The code gives each node a position, with the left child at 2p and the right child at 2p + 1, and prints the widest level. What does it print?
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
root = Node(1, Node(2, Node(4, Node(8))), Node(3, None, Node(7, None, Node(14))))
widest = 0
level = [(root, 0)]
while level:
first = level[0][1]
widest = max(widest, level[-1][1] - first + 1)
nxt = []
for node, pos in level:
if node.left:
nxt.append((node.left, 2 * (pos - first)))
if node.right:
nxt.append((node.right, 2 * (pos - first) + 1))
level = nxt
print(widest)Positions double at every level, so a deep tree breaks them in each language in its own way.
Infinity after about 1,024 levels. The width becomes NaN.The fix works in all four. At the start of each level, subtract its first position from all of them. Then no number is larger than twice the widest level.
The width itself can still be huge: a tree with a long left arm and a long right arm is 2^50,000 slots wide after 50,000 levels. So a problem promises a limit, as the warm-up does with 10^9, and the answer goes in a 64-bit integer.
Give each node a column: the root is column 0, a left child is one less than its parent, and a right child is one more. Give it a row too, which is its depth. A level-order walk finds them.
Then sort the nodes by column, then row, then value. On the tree above the answer is [[1], [3, 4], [8, 6], [10, 7, 13], [14]].
Two nodes can share a column and a row. In column 1, the nodes 7 and 13 are both on level 4, and the rule puts the smaller value first. Here the walk happens to find 7 first as well, but that is luck.
Take the root 5 with the children 3 and 7, where 3 has a right child 9 and 7 has a left child 4. The nodes 9 and 4 are both in column 0, on level 3.
The walk finds 9 first, because its parent 3 is taken before 7. The sort puts 4 first, so column 0 is [5, 4, 9].
A heap stores a tree in a plain array: the root in cell 0, and the children of the node in cell p in cells 2p + 1 and 2p + 2. These are the positions of the widest level, counted along the whole array instead of within one level. The array has no empty cell exactly when the tree is complete: every level is full, except perhaps the last, which is filled from the left.
To check it, keep the gaps in the queue. Every node adds both of its children at the back, and a missing child goes in as a gap. A gap adds nothing.
def no_gaps(root):
queue = deque([root])
gap = False
while queue:
node = queue.popleft()
if node is None:
gap = True
elif gap:
return False
else:
queue.append(node.left)
queue.append(node.right)
return TrueBefore the first gap is taken, the queue gives the cells in array order: cell 0, then 1, then 2. So every node must come before the first gap. A node after it would sit beyond an empty cell.
Take the root 1 with the children 2 and 3, where 2 has only a left child 4 and 3 has only a left child 5. No node has a right child without a left one, and yet it has a gap.
| Taken | Cell | Gap seen? | Added at the back |
|---|---|---|---|
| 1 | 0 | no | 2, 3 |
| 2 | 1 | no | 4, gap |
| 3 | 2 | no | 5, gap |
| 4 | 3 | no | gap, gap |
| gap | 4 | now yes | nothing |
| 5 | yes | stop: false |
Cell 4, the right child of 2, is empty, and node 5 sits in cell 5. The tree does not fit an array with no gap.
Predict what happens
Q A root has only a left child, and that child has two children. Does the tree fill an array with no empty cell?
Answer: B
The queue takes the root, its left child, and then a gap for the missing right child. The two grandchildren come after that gap, so they sit beyond an empty cell.
A recursive walk can pass the depth down and write each value into rows[depth]. If it visits the left child first, every row comes out left to right.
The two ways use memory differently. The queue holds about one or two levels. On a full tree of n nodes the last level has about n / 2 nodes, so the queue is large. On a chain it holds 1.
The recursion holds one call for each level of depth. On a full tree that is about log n, and on a chain it is n.
So choose the queue for a chain, and the depth-first walk for a very wide tree. The queue has one more advantage: it needs no recursion, so a chain of 100,000 nodes is no problem.
Step by step: A level-order walk on a tree built from sorted values. The animated player loads in your browser.
All the walks take n steps. What differs is how many nodes wait in the queue at once.
| Operation | Steps | Nodes waiting at once, balanced tree | Nodes waiting at once, chain | What sets the cost |
|---|---|---|---|---|
| Insert a value into a search tree | The height | None: a loop | None | Following one path |
| Search for a value | The height | None | None | Following one path |
| Delete a value | The height | None | None | Finding the node, then maybe the successor |
| Walk every level with a queue | n | About n / 2 | 1 | Every node is added and taken once |
| Average, largest or last of every level | n | About n / 2 | 1 | One pass, one summary for each round |
| Zigzag order | n | About n / 2 | 1 | Writing each value from the left or the right |
| Widest level, with positions | n | About n / 2 | 1 | One position for each node |
| Check for gaps, as for a heap | n | About n / 2, plus the gaps | 2 | Every node adds two entries, so at most 2n + 1 |
| Column view, with a sort | n log n | About n / 2 | 1 | The sort of all the nodes |
| Queue size on a balanced or a skewed tree | The widest level | About n / 2 | 1 | The shape of the tree |
Searching, inserting and deleting follow one path, so they cost the height. A level-order walk visits everything, so it costs n, and its memory depends on the shape. A balanced tree is wide at the bottom, and a chain is narrow all the way.
Use the sandbox to see the order of a level-order walk. Each level is read from left to right before the next level starts.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now build the paging behind the comment thread. The lab gives you a LevelReader class. You build a tree with set_root, add_left and add_right, and read it with next_level, has_more and restart. Every node has a value, a left link and a right link, and all three are ready for you.
The point is that the rounds are split across calls. The queue and its front must be kept between calls. Each call to next_level starts a round and takes exactly the nodes that were waiting. It leaves their children in the queue for the next call.
Three things to take care over:
next_level starts the walk. From then on the tree cannot change, so set_root, add_left and add_right return false until restart is called.Each test creates a new, empty reader, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a level-order walk when the answer is about rows: an average, the largest, a view from one side, a zigzag, a width. Use it when the order of the walk itself matters, as in a check for gaps. Use it too when you need the nodes nearest to the top first. The first leaf it finds is the shallowest one.
The walk uses a queue and no recursion, so it is safe on a chain of 100,000 nodes. Each node is handled once, so the cost is n steps.
If a node's answer needs the answers of its children, use the recursion of the last lesson, or a reverse level-order list. Examples are a height, a balance and the best path. A plain walk does not carry answers up.
On a very wide tree the queue holds about half of all the nodes. If memory is short, walk depth first and write each value into rows[depth]. That holds only the height.
while i < len(queue) as the only loop takes the children in the same round, because the length keeps growing. On the tree above the answer is one row of nine values, [[8, 3, 10, 1, 6, 14, 4, 7, 13]]. Write size = len(queue) before the round, and loop size times.
A common mistake: using the queue's length as the end of a round. The length grows as children are added, so the rows run together.
kids.reverse() before adding the children on alternate rows changes the order of later levels. On the tree above it gives [[8], [10, 3], [14, 1, 6], [13, 7, 4]]. The third row should be [1, 6, 14]. Keep the queue in order, and choose the slot when the row is written.
node = node.right until it is None gives [8, 10, 14] on the tree above and misses 13. The last node of a level can be a left child. Take the last node of each round.
width = size gives 3 for level 4 above, and the answer is 5. A width counts the empty slots between the leftmost and the rightmost node. Use positions, and the last minus the first plus one.
if node is None: return True in the check for gaps stops too early. Take the root 1 with the children 2 and 3, where 2 has only a right child 4. The first gap is the missing left child of 2, and node 4 still comes after it. Keep reading to the end of the queue, and return False for any node after a gap.
queue.pop(0) on a list moves every item behind it. For a queue of 50,000 nodes, one pop(0) moves 50,000 items. Use collections.deque and popleft(), or a list with a front position that only moves forward.
Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The queue and columns
Q1/2 Which structure gives the nodes of a tree level by level, from the top, and why?
Answer: B
A queue is first in, first out. The children of the nodes of one level are added behind them, so they are taken after the whole level.
Q2/2 In a column view, the nodes 9 and 4 share a column and a level, and the walk finds 9 first because its parent comes earlier. Ties go to the smaller value. What fixes the order?
Answer: C
The walk finds nodes in the order of their parents, which says nothing about their values. A sort with the value as the last key puts 4 before 9.
Checkpoint · Where a level ends
Q1/2 Why do you write down the queue's size at the start of a round?
Answer: B
During the round the queue grows as children are added, so its length cannot say where the level ends. The size taken before the round can.
Q2/2 At the start of a round the queue holds 5 nodes. During the round, 7 children are added. How many nodes does the next round take?
Answer: C
The round takes the 5 nodes that were waiting. The 7 children are behind them, and they are the next level, so the next round takes 7.
Checkpoint · Views and gaps
Q1/2 A tree is stored in an array as a heap is: the root in cell 0, and the children of cell p in cells 2p + 1 and 2p + 2. A level-order walk puts a gap in the queue for every missing child. When does the tree fill the array with no empty cell?
Answer: C
Before the first gap, the queue gives the cells in array order. A node after a gap would sit beyond an empty cell. The first two options miss a gap between two nodes of the last level.
Q2/2 You want the view from the right. Which is correct?
Answer: C
The view is the node furthest to the right on each level. That is the last node of the level, and it can be a left child, when nothing is to its right.
Checkpoint · Zigzag and width
Q1/2 A zigzag must read level 2 from right to left. Which change is safe?
Answer: C
The queue must give every level from left to right, so that later levels come out right. Only the place where each value is written may change.
Q2/2 Level 3 of a tree has nodes at the positions 0, 1 and 3 of a full tree. What is its width?
Answer: C
The width is the last position minus the first, plus one: 3 minus 0 plus 1 is 4. The empty slot at position 2 counts.
Checkpoint · Memory
Q1/2 A level-order walk is run on a chain of 100,000 nodes, and on a full tree of 100,000 nodes. Where does the queue hold the most nodes at once?
Answer: B
A chain has one node on every level, so the queue holds 1. A full tree has about n / 2 nodes on its last level, and the queue holds a whole level at once.
Q2/2 Which is a good queue for a level-order walk of a very wide tree in Python?
Answer: B
Taking from the front of a list moves every item behind it, which is slow for a queue of tens of thousands. A deque, or a front position, takes from the front in constant time.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.