Sub topic 3
What a Subtree Should Remember: Designing the State
This chapter assumes you know basic array DP (states, transitions, base cases), adjacency lists, depth-first search, and Big-O analysis. It also assumes you have the root_tree helper from the previous chapters. That helper returns parent, a pre-order order, and subtree size. In the reversed pre-order, every child comes before its parent.
The previous chapter gave us a traversal order. This one is about what to compute at each node as we walk that order. The answer is the state, the information a subtree hands to its parent. Most mistakes in tree DP come from a badly chosen state, not from bad code. Usually the state is too small, so the parent lacks a fact it needs. Sometimes it is too large, so the DP blows up.
The Boundary Principle
Root the tree and pick any node u. The subtree of u touches the rest of the tree through exactly one edge, the edge from u to its parent. Nothing else in the subtree is adjacent to anything outside it.
That single edge settles what the state must contain. The parent never sees inside the subtree. It only needs enough to answer two questions:
- How does a choice made inside the subtree interact with choices made outside it? Every such interaction crosses the boundary edge, so it can only involve
uitself. - How good is the best arrangement inside the subtree for each kind of interaction?
So a good state is usually "the best value inside the subtree, for each possible situation at u". The "situation at u" is whatever fact about u the parent's rules care about. Examples are whether u is chosen, what color u has, or how long a path ending at u is.
State Versus Answer
The state and the final answer are often different things. The answer is what the problem asks for. The state is what lets you build the answer bottom-up.
Here is a small example. Each node has a value. We want the length, in nodes, of the longest path that goes downward (from a node toward its descendants) and has strictly increasing values.
The answer can start at any node. But a parent can only extend a path that starts at its child. A path that starts deep inside the child's subtree is no use to the parent. So the state is:
inc[u]= length of the longest increasing downward path that starts atu.
The transition reads inc[u] = 1 + max(inc[c]) over children c with value[c] > value[u], or 1 if no child qualifies. The answer is max(inc) over all nodes. It is not inc[root].
If you stored "longest increasing path anywhere in the subtree" as the state, the parent could not extend it. It would not know whether that path starts at the child. The state has to describe what is visible at the boundary.
A Reusable Skeleton
Almost every subtree DP has the same shape:
- init(u): the state of
utreated as a single-node tree. This is also the base case for leaves. - absorb(statep, statec): fold one finished child into the parent's partial state.
- finish(state_u): an optional step that runs after all children are absorbed. You need it when the rule depends on all children together, for example "at least one child is chosen".
In the reversed pre-order, by the time we reach u, all of its children have already been absorbed into it. That makes u the right moment to finish u and then absorb it into its parent.
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 tree_fold(n, edges, init, absorb, finish=None, root=0):
parent, order, _ = root_tree(n, edges, root)
state = [init(u) for u in range(n)]
for u in reversed(order):
if finish is not None:
state[u] = finish(state[u], u)
p = parent[u]
if p != -1:
state[p] = absorb(state[p], state[u], p, u)
return state
def longest_increasing_down(n, edges, value):
def init(u):
return 1
def absorb(sp, sc, p, c):
if value[c] > value[p]:
return max(sp, sc + 1)
return sp
inc = tree_fold(n, edges, init, absorb)
return max(inc)
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
value = [5, 6, 1, 7, 2, 9]
print(longest_increasing_down(6, edges, value)) # 3: path 0 -> 1 -> 3 (5, 6, 7)Absorbing children one at a time only works if the order of children does not matter. Taking a max, summing, or adding costs all satisfy that. If your combine step behaves differently depending on child order, you have probably hidden a sequence dependency in the state, and you should rethink it.
Worked Example: A State That Must Know Its Root
Now take a problem where the answer alone cannot be passed upward.
Problem. Color every node black (1) or white (0). Some nodes have a forced color. Minimize the number of edges whose endpoints get different colors.
First attempt: store only the best cost
Say best[u] is the minimum number of mismatched edges inside u's subtree. When the parent p absorbs child c, it must decide whether the edge (p, c) is a mismatch. That depends on the color of c in the optimal coloring of c's subtree. best[c] does not record that color. There may even be two optimal colorings with different colors at c. The state is too small.
Fixed state: index by the color at the boundary
The only fact that crosses the boundary edge is the color of c. So we keep one value per color:
cost[u][x]= minimum mismatches insideu's subtree, given thatuhas colorx. The value is infinity ifuis forced to the other color.
When the parent has color x, the child can match it for free or take the other color and pay 1 for the edge:
cost[p][x] += min(cost[c][x], cost[c][1 - x] + 1)
The base case is a lone node: cost[u] = [0, 0], with the forbidden color set to infinity. The answer is min(cost[root][0], cost[root][1]).
import itertools
import random
INF = float('inf')
def min_mismatch_coloring(n, edges, forced, root=0):
# forced[u] is None, 0, or 1
def init(u):
s = [0, 0]
if forced[u] is not None:
s[1 - forced[u]] = INF
return s
def absorb(sp, sc, p, c):
return [
sp[0] + min(sc[0], sc[1] + 1),
sp[1] + min(sc[1], sc[0] + 1),
]
cost = tree_fold(n, edges, init, absorb, root=root)
return min(cost[root])
def brute_force(n, edges, forced):
best = INF
for colors in itertools.product((0, 1), repeat=n):
if any(f is not None and colors[u] != f for u, f in enumerate(forced)):
continue
best = min(best, sum(colors[u] != colors[v] for u, v in edges))
return best
random.seed(1)
for _ in range(500):
n = random.randint(1, 9)
edges = [(v, random.randrange(v)) for v in range(1, n)]
forced = [random.choice([None, None, 0, 1]) for _ in range(n)]
assert min_mismatch_coloring(n, edges, forced) == brute_force(n, edges, forced)
print("all random tests passed")Every node is forced to some color in its own subtree only by its own init. Because of that, cost[u][x] is always finite for at least one x, and the answer is always finite. Adding to infinity stays infinity in Python floats, so forbidden options never leak into a finite total.
A Design Checklist
Use these steps for every new problem:
- Name the boundary fact. What property of
udo the rules that involve the parent edge depend on? Chosen or not, a color, the depth of the deepest open path, the number of selected nodes. Index the state by it. - Name the value. For each boundary fact, store the best cost, the best score, or a count of arrangements inside the subtree.
- Write the leaf case. A single node with no children has to give correct values. Often this is the same as
init. - Write absorb. Check that it ignores child order and that the work done for each child does not depend on how many children came before it.
- Separate the answer. Decide whether the answer is read at the root or collected as a running best over all nodes.
- Estimate the cost. The total time is about the number of edges times the cost of one absorb. A state with
sentries and a pairwise combine costsO(s^2)per edge.
Too Small, Right, Too Large
| Problem | State too small | Right-sized state | State too large |
|---|---|---|---|
| Two-color mismatch | best cost only | cost for each color of `u` | the full coloring of the subtree |
| Longest increasing downward path | best path anywhere in subtree | longest path starting at `u` | every path in the subtree |
| Count nodes in subtree | (none) | one integer | the list of nodes |
| Max path sum (later chapter) | best path anywhere | best downward path from `u`, plus a running global best | all root-to-leaf sums |
A state that is too small gives wrong answers, often only on some inputs, so it can pass small hand tests. A state that is too large gives correct answers but makes the DP exponential or quadratic in memory. The target is the smallest summary that still lets the parent apply its rules.
Indexing by Your Own Choice or the Parent's
There are two equivalent ways to handle a constraint on an edge:
- Index by your own choice (as above):
cost[c][x]assumeschas colorx, and the parent loops over both of its own options. - Index by the parent's choice:
cost[c][y]assumes the parent ofchas colory, andchas already minimized over its own color.
The first form is more common. It keeps each node's state about the node itself, and it works the same way at the root, which has no parent. The second form can make the combine step simpler, but you then need a special case at the root. Pick one form per problem and do not mix them. Mixing them is a frequent source of off-by-one-edge bugs.
Common Errors
- Reading the answer from the root when it lives elsewhere. If the best structure need not touch the root, as with longest increasing paths or diameters, keep a running global best.
- Double counting the boundary edge. Count the cost or contribution of edge
(p, c)exactly once. Count it inp's absorb step, never also inc's finish step. - Initializing with 0 where "impossible" is needed. Forbidden states must be infinity when minimizing, minus infinity when maximizing, and 0 when counting. A 0 in a minimization makes an illegal option look free.
- Rules that need all children at once. Constraints like "exactly one child is selected" cannot be checked inside a single absorb step unless the partial state tracks progress, for example "zero selected so far" versus "one selected so far". Add that counter to the state, or resolve it in
finish. - Recursion depth. A recursive DFS over a path-shaped tree of 10^5 nodes crashes Python's default stack. The iterative
tree_foldavoids this.
Exercises
Exercise
Each node has an integer weight, possibly negative. You want the maximum total weight of a connected set of nodes that contains its own topmost node u and lies inside u's subtree. What state do you store, and what is the absorb rule?
Show answer
Store best[u] = maximum weight of a connected set whose topmost node is u. Initialize best[u] = weight[u]. Absorb each child with best[p] += max(0, best[c]): a child's piece is attached only if it helps. The answer to "best connected set anywhere" is max(best) over all nodes, not best[root].
Exercise
In the two-color mismatch problem, suppose mismatched edges have individual weights w(p, c) instead of cost 1. Which line of the code changes, and does the state need to change?
Show answer
Only the absorb rule changes: cost[p][x] += min(cost[c][x], cost[c][1 - x] + w(p, c)). The state stays the same, because the only fact crossing the boundary edge is still the color of c.
Exercise
A friend stores, for the increasing-path problem, inc[u] = longest increasing downward path anywhere in u's subtree, and computes the answer as inc[root]. Give a tree on which this fails, and explain why.
Show answer
Take edges (0,1), (1,2) with values [9, 1, 2]. The best path is 1 -> 2, of length 2. Under the friend's definition, inc[1] = 2 is correct, but node 0 cannot tell whether that path starts at node 1. If the transition assumes it does and extends it to 0, the value check uses only value[1] > value[0] (false here), so it happens to stay correct. Changing values to [0, 5, 1] breaks it: the path 1 -> 2 is not increasing, so node 1's longest increasing path anywhere is 1. With edge (1,3) and value[3] = 3 added, the path 2 -> ... is missing, while 0 -> 1 has length 2, and a subtree path deeper down (for example 2 -> 4 -> 5 with increasing values) can be counted as extendable by 0 even though it does not start at 1. The fix is to store the path that starts at u and track a separate global maximum.