Sub topic 3
What a Subtree Should Remember: Designing the State
This chapter assumes you know basic array DP (states, transitions, base cases) and can read Python. It also assumes you have the root_tree helper from the previous chapter, which returns parent, a children-before-parents order, and subtree sizes. Here we cover the design step that comes before any tree DP code: choosing what each subtree reports to its parent.
The contract between child and parent
In tree DP, each node u stands for its whole subtree. When the post-order pass reaches u, all its children are finished, and u can see only what they recorded. Their own descendants are out of reach. The state is that recorded summary. It is the contract between a child and its parent.
A good state passes three tests:
- Sufficient. The parent can compute its own state from its children's states plus its own data.
- Small. It fits in a constant number of values, or in a table whose size is bounded by some parameter such as
k. - Anchored. It describes a precise relationship to
u, such as "the path starts atu" or "uis chosen". Vague descriptions like "the best thing somewhere below" fail this test.
A worked design: best downward path
Problem. Every node has an integer value, which may be negative. For each node u, find the largest sum of a path that starts at u and goes only downward.
First attempt. Let best[u] mean "the largest path sum anywhere in u's subtree." This fails the anchored test. The parent cannot extend that path, because it may not touch the child at all.
Fixed state. Let down[u] be the largest sum of a downward path that starts at u. A path starting at u either stops at u or continues into exactly one child, starting at that child. So:
- Base case: a leaf has
down[u] = value[u]. - Transition:
down[u] = value[u] + max(0, max over children c of down[c]).
The max(0, ...) handles the choice to stop at u when every child path is negative.
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, size
def best_downward_path(n, edges, value, root=0):
parent, order, _ = root_tree(n, edges, root)
best_child = [0] * n # max(0, best down[c]) seen so far
down = [0] * n
for u in reversed(order):
down[u] = value[u] + best_child[u]
p = parent[u]
if p != -1 and down[u] > best_child[p]:
best_child[p] = down[u]
return down
edges = [(0, 1), (0, 2), (1, 3), (1, 4)]
value = [2, -1, -5, 4, -3]
print(best_downward_path(5, edges, value)) # [5, 3, -5, 4, -3]Check node 1. Its children report 4 and -3, so it extends into node 3 and gets -1 + 4 = 3. Node 0 compares 3 (from node 1) with -5 (from node 2) and gets 2 + 3 = 5. Every node's transition finishes before its parent runs because reversed(order) visits children first.
When one number is not enough
Some problems need the state to keep track of a choice made at u, because that choice limits what the parent may do. If the parent cannot decide without knowing that choice, split the state.
| Problem | State per node | Why this shape |
|---|---|---|
| Subtree size | one integer | Sizes simply add up |
| Best downward path | one integer, anchored at `u` | The parent extends exactly one child path |
| Independent set | two values: `u` taken / `u` skipped | Taking the parent forbids taking the child |
| Pick exactly `k` nodes | table indexed by count `j ≤ k` | The parent must split its budget among children |
The last two rows are covered in later chapters. The design method is the same each time: ask what the parent needs to know, and store exactly that.
Common errors
- Missing the empty or stop option. Forgetting the
max(0, ...)above makes every path run down to a leaf. - Mixing the answer with the state. The quantity the parent extends and the final global answer often differ. Keep them in separate variables. The next chapters on diameter make this concrete.
- States that grow with subtree size. Storing a full list per node can make the whole pass O(n²). Look for a summary of fixed size first.
Exercises
Exercise
You need, for every node u, the minimum value anywhere in u's subtree. State the DP state, base case, and transition. Is anchoring needed here?
Show answer
State mn[u] = minimum value in u's subtree. Base case for a leaf: mn[u] = value[u]. Transition: mn[u] = min(value[u], min over children c of mn[c]). No anchoring is needed, because the minimum of a union of sets equals the minimum of the parts. The parent never has to extend anything; it only combines.
Exercise
A student defines down[u] as "the largest downward path sum in u's subtree" without requiring that the path start at u, and then uses down[u] = value[u] + max(0, max down[c]). Give a tree where this gives a wrong answer for the path starting at the root.
Show answer
Take the path 0 - 1 - 2 with values [1, -10, 5]. Under the student's definition, down[1] = 5, because the best path in node 1's subtree is node 2 alone. The root then gets 1 + 5 = 6, which uses a path that skips node 1 and is not connected. The correct value is down[1] = -10 + 5 = -5, so the root keeps only itself and gets 1.