Three problems where the best answer for a tree comes from small answers for its subtrees. The move: each node returns a short tuple of states, and its parent combines only its children's tuples.
You work on a freight app, a streaming app and a hiking app. Each one has a tree, and each asks for a best value. The catch is that a choice at one node limits the choices around it.
A depot that is emptied blocks its neighbours. A route that turned left must turn right next. A tower at a junction covers its neighbours. A greedy rule that looks at one node at a time fails, because the right choice depends on the nodes below.
| Problem | The choice at a node | The tuple a node returns |
|---|---|---|
| Collect parcels from unlinked depots | empty it or leave it | the best total with it, and without it |
| Longest left-right-left route | the first move from the node | the longest route that starts left, and that starts right |
| Signal towers along a trail network | put a tower here or not | uncovered, covered without a tower, or has a tower |
The first tree has the parcels 3, 4, 5, 1, 3 and 1. Node 0 has the children 1 and 2. Node 1 has the children 3 and 4, and node 2 has the right child 5. The table gives the two totals of each node, from the bottom up.
| Node | Parcels | Total if taken | Total if left |
|---|---|---|---|
| 3 | 1 | 1 | 0 |
| 4 | 3 | 3 | 0 |
| 5 | 1 | 1 | 0 |
| 1 | 4 | 4 | 4 |
| 2 | 5 | 5 | 1 |
| 0 | 3 | 8 | 9 |
The best total is 9: the depots 1 and 2. A rule that takes every second level gets 8 or 9 here, but it fails on other trees. Take the parcels 2, 8, 9 and 3, where node 0 has the children 1 and 3, and node 1 has the left child 2. Its levels add up to 2, 11 and 9, so the best second-level rule gives 11, and the right answer is 12: the depots 2 and 3.
Exercise · Predict the output: The best total of the first tree. The code computes the two totals for every node, children before parents. The parcels are 3, 4, 5, 1, 3, 1. What does it print?
parcels = [3, 4, 5, 1, 3, 1]
left = [1, 3, -1, -1, -1, -1]
right = [2, 4, 5, -1, -1, -1]
order = [0]
for node in order:
for child in (left[node], right[node]):
if child != -1:
order.append(child)
take = [0] * len(parcels)
skip = [0] * len(parcels)
for node in reversed(order):
take[node] = parcels[node]
for child in (left[node], right[node]):
if child != -1:
take[node] += skip[child]
skip[node] += max(take[child], skip[child])
print(max(take[0], skip[0]))Ask what the parent needs to know about a subtree. For the houses it needs two numbers: the best total if the child is taken, and the best total if it is left. That is enough, because the parent never looks deeper than its children.
So every node returns a tuple with one entry for each situation. The parent builds its own tuple from the tuples of its children. The tuple has a fixed size, so each node costs a constant amount of work.
Each node returns a short tuple that holds the best answer for each situation of its parent. The parent uses only the tuples of its children, so each node is solved once.
For the houses, taking a node adds its parcels and the left totals of its children. Leaving a node adds the better total of each child. The answer is the better of the two totals of the top.
Each depot returns two totals. Taking it adds the left totals of its children, and leaving it adds their better totals.
The same move works for a route. Let each node return the longest route that starts with a move left, and the longest that starts with a move right. A move left goes to the left child and then must continue with a move right from there.
Take five nodes in a line, where the moves from the top are right, right, left and right. The pairs are (0, 0) for node 4 and (0, 1) for node 3. For node 2 the pair is (2, 0), for node 1 it is (0, 3), and for node 0 it is (0, 1).
The longest route is 3 choices and it starts at node 1, not at the top. The top gives only 1. So for a route the answer is the best value over all nodes.
Exercise · Find the bug: The taken totals of the children. This finds the most parcels from depots that are not linked. It computes the children before their parents. For one tree it returns too much. Which line is wrong?
def most_parcels(parcels, left, right):
n = len(parcels)
order = [0]
for node in order:
for child in (left[node], right[node]):
if child != -1:
order.append(child)
take = [0] * n
skip = [0] * n
for node in reversed(order):
take[node] = parcels[node]
for child in (left[node], right[node]):
if child != -1:
take[node] += take[child]
skip[node] += max(take[child], skip[child])
return max(take[0], skip[0])The Academy lessons Tree recursion and Memoisation teaser return one number from each node, such as a height, and cache repeated work. This street does not teach those again. It changes three things.
A node returns a tuple. One number is not enough when a choice at the node limits the parent. The tuple holds one answer for each situation, and its size stays fixed.
The tuple replaces the cache. Without it, a plain recursion for the houses recomputes the grandchildren. On a chain of 30 depots it makes 7,049,153 calls, and with the tuple the same chain needs 30. The tuple is the memo, stored in the return value.
The answer may sit anywhere. For the zigzag route, keep the best value seen at every node, not the value of the top. Reading only the top of the five-node tree above gives 1, and the right answer is 3.
Process children before parents without recursion. A chain of 100,000 nodes is allowed. A recursive version of the houses code works on a chain of 900 depots and raises a recursion error on one of 1,500 in Python.
The tower problem has three states: a junction is not covered, covered without a tower, or holds a tower. Go from the bottom up. A tower goes on a junction when a child is not covered, and a junction with a tower child is covered. Otherwise it stays not covered, and its parent must handle it.
Exercise · Break it: The zigzag read only at the top. This finds the longest alternating route. It computes the two route lengths for every node, but it reports only the top. Find a tree where it gives a wrong answer.
def longest_alternating_route(left, right):
n = len(left)
order = [0]
for node in order:
for child in (left[node], right[node]):
if child != -1:
order.append(child)
go_left = [0] * n
go_right = [0] * n
for node in reversed(order):
if left[node] != -1:
go_left[node] = 1 + go_right[left[node]]
if right[node] != -1:
go_right[node] = 1 + go_left[right[node]]
return max(go_left[0], go_right[0])A zigzag route can start at any node, so keep the best value over all nodes, not the value at the top.
Solve them in this order. The first has two totals, the second has two route lengths and a best over all nodes, and the third has three states.
Before you code each problem, write three lines. What does a node return, what does the parent do with it, and where is the answer read? If the tuple has more than a handful of entries, look for a smaller one.
Give each problem about 25 minutes. Draw the first tree of this lesson and fill in the tuples from the bottom up, by hand. Then code it, and compare your table with a printout.
Test a single node, a chain and a tree where the best choice skips a heavy node. A chain of 100,000 nodes rules out recursion. For the towers, a chain of five junctions needs 2.
When an answer is wrong, print the tuple of every node. A wrong entry usually shows in a leaf, or in a node whose child is missing.
Checkpoint · Tree DP
Q1/5 What does a node return in a tree DP?
Answer: B
One number is not enough when a choice at the node limits its parent. The tuple holds the answer for each situation, and the parent uses only the tuples of its children.
Q2/5 Linked depots cannot both be emptied. A depot is taken. What does its total add from each child?
Answer: B
A taken depot blocks its children, so only their left totals can be added. A depot that is left adds the better total of each child.
Q3/5 The parcels are 2, 8, 9 and 3. Node 0 has the children 1 and 3, and node 1 has the left child 2. Why does taking every second level fail?
Answer: B
The levels add up to 2, 11 and 9. The second-level rule gives 11, but the depots with 9 and 3 are not linked and give 12.
Q4/5 In the zigzag problem, why do you keep the best value seen at every node?
Answer: B
The top of the example tree gives a route of 1, but a route that starts at its child has 3 choices. The answer is the best value over all nodes.
Q5/5 In the tower problem a junction has a child that is not covered. What does the junction do?
Answer: C
A child that is not covered can only be covered from its parent or from itself. The tower on the parent covers it, and it also covers the parent's own parent.
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.