Three problems where a tree is an ordinary graph: no root is needed, and a rule can spread up as well as down. The move: build both-way neighbour lists, then spread from one start or inward from the leaves.
You work on a payments app, a search app and a ride-hailing app. Each one has a tree, and each one asks how long a rule takes to reach every node. The three problems on this street ask that question in three ways.
A tree is a graph. It has n - 1 edges, and exactly one path joins any two nodes. The input names only one direction, a manager for each person or a left and a right child. The rule of the problem may go the other way as well.
| Problem | The input gives | The rule spreads | The tool |
|---|---|---|---|
| Minutes to inform every employee | the manager of each person | down, with a cost at each manager | reports lists, then the longest weighted path |
| Time to burn the tree | left and right children | down and up | neighbour lists with the parent, then a queue |
| Smallest height trees of a network | two-way roads | from the leaves inward | degrees, then peel the leaves |
The street uses three small examples. Take seven pages in a full tree, with the children [1, 2] for node 0, [3, 4] for node 1 and [5, 6] for node 2. A stale mark starts at page 1.
After one minute, pages 0, 3 and 4 are stale. After two, page 2 joins them. After three, pages 5 and 6 join, so all seven are stale in 3 minutes.
Exercise · Predict the output: The zones that remain. Six zones are joined by the roads 0-3, 1-3, 2-3, 4-3 and 5-4. The code removes leaves in rounds while more than two zones remain. What does it print?
zones = 6
roads = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
adjacent = [[] for _ in range(zones)]
for a, b in roads:
adjacent[a].append(b)
adjacent[b].append(a)
degree = [len(x) for x in adjacent]
leaves = [i for i in range(zones) if degree[i] == 1]
remaining = zones
while remaining > 2:
remaining -= len(leaves)
following = []
for leaf in leaves:
for other in adjacent[leaf]:
degree[other] -= 1
if degree[other] == 1:
following.append(other)
leaves = following
print(*sorted(leaves))Turn the input into a neighbour list for every node. For a parent list, add each person to their manager's list. For left and right children, add the child to its parent and the parent to the child.
Then spread. With a start node, use a queue and a distance array, and mark each node when you first reach it. Without a root, count the neighbours of every node, and peel the leaves.
With neighbour lists in both directions, a spread from one start reaches each node once, along the only path. So the first visit gives the distance, and no later visit can improve it.
From a start at page 1 on the seven pages, pages 0, 3 and 4 are at distance 1. Page 2 is at 2, and pages 5 and 6 are at 3. The answer is the largest distance: 3.
With the parent in every list, a queue search from one page reaches each page once, and the first visit gives its distance.
For the on-call tree, the rule spreads down only, but each manager adds a cost. Take six people: the head 0 needs 2 minutes to inform its reports, 1 and 2. Person 1 needs 3 minutes for 3 and 4, and person 2 needs 1 minute for 5.
Person 1 hears at minute 2, and persons 3 and 4 at minute 5. Person 5 hears at minute 3. The last person hears at minute 5, the largest arrival time.
Exercise · Find the bug: The link to the parent. This builds the neighbour lists of a page tree and returns how many neighbours one page has. For a page below the top it counts too few. Which line is wrong?
def count_neighbours(left, right, node):
n = len(left)
adjacent = [[] for _ in range(n)]
for parent in range(n):
for child in (left[parent], right[parent]):
if child != -1:
adjacent[parent].append(child)
return len(adjacent[node])The Academy lessons Trees and binary search trees, Graphs and BFS and DFS on any graph cover trees, graphs and the queue search. This street does not teach them again. It changes three things.
The input is one form of a neighbour list. A parent list, a pair of child lists and a list of roads all become the same neighbour lists. After that, the problem does not care which form it came in.
The upward link is the whole difference. A search that follows only the children from page 1 reaches 1, 3 and 4 and stops: the answer is 1, not 3. A tree problem that moves up needs the parent in every list, or a parent array that you follow as a second neighbour.
A cost can sit on the node. In the on-call tree, adding up all the waiting times gives 6, but the answer is the largest arrival time, 5. The times of managers on other branches do not add up.
There may be no root. For the best hub, try every zone as a root, and it costs n searches of n steps: 10,000,000,000 for 100,000 zones. Peel the leaves instead. A path of 100,000 zones takes 49,999 rounds, and the total work is still n.
Peel until at most two zones remain. If you stop at one, a tree with two centres gives an empty answer. On a path of four zones, the right answer is zones 1 and 2.
Exercise · Break it: The peeling that stops at one. This peels the leaves while more than one zone remains, and returns the last leaves. Find a road tree where it gives a wrong answer.
def best_hubs(zones, roads):
if zones == 1:
return [0]
adjacent = [[] for _ in range(zones)]
for a, b in roads:
adjacent[a].append(b)
adjacent[b].append(a)
degree = [len(x) for x in adjacent]
leaves = [i for i in range(zones) if degree[i] == 1]
remaining = zones
while remaining > 1:
remaining -= len(leaves)
following = []
for leaf in leaves:
for other in adjacent[leaf]:
degree[other] -= 1
if degree[other] == 1:
following.append(other)
leaves = following
return sorted(leaves)Without the parent in each list, a search from a page below the top never reaches the pages above it.
Solve them in this order. The first spreads down with a cost, the second spreads both ways, and the third has no root at all.
Before you code each problem, write three lines. What does the input name, which way does the rule spread, and what is measured at the end? Then build the neighbour lists to match.
Give each problem about 20 minutes. Draw the example tree and number the minutes by hand. Then write the neighbour lists, and compare your numbers with a printout.
Test a single node, a chain and a start at a leaf. The single node has answer 0, and the chain of 100,000 nodes rules out recursion, so use a queue.
When a spread is wrong, print the neighbour list of one node below the top. If its parent is missing, the upward link is the problem.
Checkpoint · Trees as graphs
Q1/5 A stale mark starts at a page below the top and spreads to linked pages, up and down. What must the neighbour list of each node hold?
Answer: B
The rule spreads upward as well. Without the parent, a search from page 1 of the seven-page tree reaches only 1, 3 and 4 and reports 1 instead of 3.
Q2/5 Why does the first time a queue search reaches a node give the right distance in a tree?
Answer: B
With one path between two nodes, there is no shorter way to find later. The first visit uses that path.
Q3/5 The head needs 2 minutes to inform its reports, person 1 needs 3, and person 2 needs 1. The last person hears at minute 5. Why is the answer not the sum of all waiting times, which is 6?
Answer: B
Reports of different managers hear at the same moment. The answer is the largest sum along one branch from the head.
Q4/5 Six zones are joined by the roads 0-3, 1-3, 2-3, 4-3 and 5-4. Which zones remain after the leaves are removed round by round?
Answer: B
The leaves 0, 1, 2 and 5 go first. Zones 3 and 4 remain, and both have the smallest reach, which is 2.
Q5/5 Why must the peeling stop when two zones remain, and not when one remains?
Answer: C
On a path of four zones the answer is zones 1 and 2. Stopping at one removes them in the last round and returns an empty list.
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.