Four problems that report a tree one level at a time, or one column at a time. The move: take a snapshot of the queue at each round, and keep one small summary for each level.
You work on an ad platform, a social app, a monitoring system and a page builder. Each one stores a tree, and each one needs a report that groups its nodes. Most groups are the levels of the tree. One group is a column.
The four problems on this street are four reports. The queue loop is the same for all of them. What changes is the small summary that you keep for each group.
| Problem | The group | What you keep for it |
|---|---|---|
| Average of every level | a level | a total and a count |
| Bottom-up level order | a level | the list of its codes, reversed at the end |
| Largest value on each level | a level | the largest code so far |
| Column-by-column view | a column | the codes with their rows |
The street uses one small tree. Its codes are 1, 2, 3, 6 and 5. Node 0 has the children 1 and 2, node 1 has the right child 3, and node 2 has the left child 4. The levels are [1], [2, 3] and [6, 5].
Exercise · Predict the output: The largest code of each level. The codes are 4, -2, 7, 1, 9 on the street shape: node 0 has the children 1 and 2, node 1 has the right child 3, and node 2 has the left child 4. What does this print?
from collections import deque
values = [4, -2, 7, 1, 9]
left = [1, -1, 4, -1, -1]
right = [2, 3, -1, -1, -1]
queue = deque([0])
out = []
while queue:
best = values[queue[0]]
for _ in range(len(queue)):
node = queue.popleft()
best = max(best, values[node])
if left[node] != -1:
queue.append(left[node])
if right[node] != -1:
queue.append(right[node])
out.append(best)
print(*out)Put the top in a queue. Each round, read the size of the queue before you take anything. At that moment the queue holds exactly one level, from left to right.
Take that many nodes. For each one, update the summary of the level and push its children. When the round ends, the queue holds the next level.
At the start of each round the queue holds exactly one level, left to right. Reading the size first keeps the children that you push out of this round.
Then the summary resets, and the next round starts. On the street tree the three rounds see the queue sizes 1, 2 and 2.
Read the queue size first: the queue then holds exactly one level, and the children you push are the next level.
For the average, the summary is a total and a count, and the average rounds down. The total can be large: a million for each of 100,000 codes is 100,000,000,000, which does not fit in a 32-bit int, so use a 64-bit total.
For the largest code, the summary starts as the first code of the level and not as 0, because the codes can be negative.
Exercise · Break it: The maximum that starts at zero. This reports the largest code of each level. It starts every level with a best of 0. Find a tree where a level has the wrong largest code.
def largest_per_level(values, left, right):
result = []
level = [0] if values else []
while level:
best = 0
following = []
for node in level:
best = max(best, values[node])
if left[node] != -1:
following.append(left[node])
if right[node] != -1:
following.append(right[node])
result.append(best)
level = following
return resultThe Academy lessons Level order and views and Queues and deques teach the level loop and the queue. This street does not teach them again. It changes three things.
The summary changes, the loop does not. A total and a count give the average. A maximum gives the slowest call of each depth. A list of the codes gives the report itself.
A bottom-up report is the same report, reversed. Collect the levels from the top and reverse the list once. Do not insert each level at the front of the list: for a chain of 100,000 levels, that shifts 4,999,950,000 items in all.
A column view has two coordinates. A left child goes one column left and one row down. A right child goes one column right and one row down. The queue order alone is not enough.
On the street tree, node 3 is the right child of node 1, and node 4 is the left child of node 2. Both land in column 0 and row 2, with the codes 6 and 5. The queue reaches 6 first, so a sort by column and row alone gives [1, 6, 5] for column 0, and the right answer is [1, 5, 6].
Exercise · Find the bug: Two nodes in one cell. Each entry is a column, a row and a code. This orders the entries by column, then row, and returns the codes. Two nodes share a column and a row. Which line is wrong?
def sort_cells(entries):
entries.sort(key=lambda e: (e[0], e[1]))
return [e[2] for e in entries]Two nodes can share a column and a row. Sort by column, row and then code.
Solve them in this order. The first three share the level loop with a different summary. The last one adds coordinates and a full sort.
Before you code each problem, write two lines: what is the group, and what small summary do I keep for it? Say whether the summary resets every round.
Give each problem about 20 minutes. Draw the street tree and write the groups by hand. For the column view, write the column and the row of every node.
Test an empty tree, a single node, a chain and a tree where a level holds only negative codes. For the column view, add the tie of nodes 3 and 4.
When a report is wrong, print the size of the queue at the start of each round. A wrong size is the most common error: the levels run into each other.
Checkpoint · Level order views
Q1/5 Why do you read the size of the queue at the start of each round, before you take any node?
Answer: B
Reading the size fixes the level. Children are pushed during the round, and they belong to the next one.
Q2/5 You add up the codes of a level to find its average. The codes are up to a million, and a tree has 100,000 nodes. What type should the total be?
Answer: B
A million times 100,000 is 100,000,000,000, far above 2,147,483,647. The average rounds down, so an integer division of the 64-bit total is right.
Q3/5 The codes on a level can be negative. How should the maximum of a level start?
Answer: C
A start of 0 is larger than every negative code, so a level of negative codes would report 0, which is not one of its codes.
Q4/5 How do you list the levels from the bottom up without a slow insert at the front?
Answer: C
An insert at the front of a list with L levels shifts every item. For a chain of 100,000 levels that is 4,999,950,000 shifts. One reversal costs L steps.
Q5/5 Two nodes land in the same column and the same row, and the problem wants the smaller code first. What must the sort key be?
Answer: C
A sort by column and row keeps the queue order for a tie, which is not the order asked for. The code is the last part of the key.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.