Sub topic 9
Tree Knapsack: Merging Child Tables
The earlier chapters stored a few numbers per subtree. A size, a depth, or a pair of take/skip values was enough. Some problems need more than that, because the answer depends on how much of a budget each subtree uses. In those problems every node stores a whole table indexed by budget, and the parent's table is built by merging its children's tables one at a time. This pattern is called tree knapsack.
This chapter assumes you know 0/1 knapsack on arrays, the root_tree helper and reversed pre-order processing from the earlier chapters, and Big-O analysis. Complexity comes up here only as far as writing the loops correctly requires. The proof of the O(n·k) bound is in the next chapter.
The Problem
You are given a tree with n nodes, a value on each node, and a budget k. You must choose exactly k nodes that form a connected set and include the root, and you want the largest total value. Requiring the root and connectivity is the same as saying "a node may be chosen only if its parent is chosen." The same structure appears in other forms:
- Courses with prerequisites, where you can take at most
kcourses and each course needs its parent course. - Picking
kcities to keep on a road network, where the kept cities must stay connected to the capital. - Opening
kfolders in a file tree, where each folder can only be opened after its parent.
A greedy approach fails. The best single child may lead to a poor branch, and a child with a small value may guard a very valuable grandchild.
Designing the State
Ask what a parent needs to know about a child's subtree. It needs to know: "if I spend j nodes inside this child's subtree, what is the best value I can get?" One number is not enough to answer that, so each subtree keeps a table.
Define:
dp[u][j]is the maximum total value of a connected set of exactlyjnodes that containsuand lies insideu's subtree.
Requiring u to be in the set is what makes the merge valid. A chosen set in a child's subtree that contains the child is automatically connected to the parent once the parent is chosen. If the state allowed sets that do not contain u, the parent could attach a disconnected piece.
Base case: a lone node has dp[u] = [-inf, value[u]]. Index 0 is impossible because the set must contain u, so it holds negative infinity. Index 1 is the node alone.
The Merge Step
Process the children of u one by one. Before the first child, dp[u] covers only u itself. After a child c is merged, dp[u] covers u plus every child merged so far. Merging child c means choosing how many nodes j to spend in c's subtree:
- Spend 0 nodes in
c: keepdp[u][i]as it was. - Spend
j ≥ 1nodes inc: combine to getdp[u][i] + dp[c][j]at indexi + j.
This is a max-plus convolution of the two tables. In knapsack terms, each child is a group of items, and you may take at most one item from the group: "spend exactly j here."
Two details matter. The new table is written into a separate list, merged, because updating a in place would let one child contribute twice, in the same way that iterating the wrong direction in 1D 0/1 knapsack lets an item be reused. The second detail is capping: no table ever needs an index above k, and no table can have an index above the number of nodes it covers.
The Implementation
The code below includes the root_tree helper so it runs on its own. Because order is a pre-order, reversed order visits every node after all of its descendants. When the loop reaches child u, every child of u has already been merged into dp[u], so the table is final and can be merged upward.
NEG = float('-inf')
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_rooted_subtree(n, edges, value, k, root=0):
# dp[u][j]: max total value of a connected set of j nodes
# that contains u and lies inside u's subtree (k >= 1)
parent, order, _ = root_tree(n, edges, root)
dp = [[NEG, value[u]] for u in range(n)]
for u in reversed(order):
p = parent[u]
if p == -1:
continue
a, b = dp[p], dp[u]
merged = list(a) + [NEG] * (min(len(a) + len(b) - 1, k + 1) - len(a))
for i in range(1, len(a)):
if a[i] == NEG:
continue
for j in range(1, len(b)):
if i + j > k:
break
if a[i] + b[j] > merged[i + j]:
merged[i + j] = a[i] + b[j]
dp[p] = merged
dp[u] = None
r = dp[root]
return r[k] if k < len(r) else None
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
value = [1, 5, 4, 7, 3, 9]
print(best_rooted_subtree(6, edges, value, 3)) # 14
print(best_rooted_subtree(6, edges, value, 4)) # 19
print(best_rooted_subtree(6, edges, value, 7)) # NoneHere is what each line of the merge does:
mergedstarts as a copy ofa, which covers the case "spend 0 nodes in this child." It is padded withNEGup to lengthmin(len(a) + len(b) - 1, k + 1). A table of lengthLcovers counts 0 throughL - 1, so combining counts up tolen(a) - 1andlen(b) - 1gives counts up tolen(a) + len(b) - 2. That is the- 1in the length.- Both loops start at 1 because index 0 is always impossible.
breakoni + j > kis safe becausejonly grows inside the inner loop.dp[u] = Nonefrees the child's table. Each table is used exactly once, and freeing it keeps memory near the size of the tables currently being built instead ofn · k.
The final line returns None when the tree has fewer than k nodes. Otherwise r[k] is a real value: a connected set containing the root can have any size from 1 up to the subtree size, since you can always grow it by adding a neighbor.
Tracing the Example
The tree has root 0 with children 1 and 2. Node 1 has children 3 and 4, and node 2 has child 5. The values are [1, 5, 4, 7, 3, 9] and k = 3. root_tree produces the order [0, 2, 5, 1, 4, 3], so the reversed order is 3, 4, 1, 5, 2, 0.
| Step | Merge | Parent table before | Child table | Parent table after |
|---|---|---|---|---|
| 1 | 3 into 1 | `[-, 5]` | `[-, 7]` | `[-, 5, 12]` |
| 2 | 4 into 1 | `[-, 5, 12]` | `[-, 3]` | `[-, 5, 12, 15]` |
| 3 | 1 into 0 | `[-, 1]` | `[-, 5, 12, 15]` | `[-, 1, 6, 13]` |
| 4 | 5 into 2 | `[-, 4]` | `[-, 9]` | `[-, 4, 13]` |
| 5 | 2 into 0 | `[-, 1, 6, 13]` | `[-, 4, 13]` | `[-, 1, 6, 14]` |
Step 3 shows the cap at work. Node 1's table has an entry for 3 nodes (value 15), but combining it with the root's 1 node would need 4 nodes, so the break skips it. In step 5, index 3 improves from 13 ({0, 1, 3}) to 14 ({0, 2, 5}) by spending 2 nodes in node 2's subtree, which gives 1 + 13. Index 2 stays at 6 because {0, 1} beats {0, 2}.
Checking Against Brute Force
Table-merging code fails quietly when it has an off-by-one in the lengths. A brute-force checker on small random trees catches those bugs fast. The script below assumes the code above is saved as tree_knapsack.py.
import random
from itertools import combinations
from tree_knapsack import best_rooted_subtree
def brute(n, edges, value, k, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
best = None
for combo in combinations(range(n), k):
s = set(combo)
if root not in s:
continue
seen = {root}
stack = [root]
while stack:
u = stack.pop()
for v in adj[u]:
if v in s and v not in seen:
seen.add(v)
stack.append(v)
if len(seen) == k:
total = sum(value[x] for x in s)
if best is None or total > best:
best = total
return best
for trial in range(500):
n = random.randint(1, 8)
edges = [(i, random.randrange(i)) for i in range(1, n)]
value = [random.randint(-5, 10) for _ in range(n)]
k = random.randint(1, n + 1)
assert best_rooted_subtree(n, edges, value, k) == brute(n, edges, value, k), \
(n, edges, value, k)
print("all tests passed")Negative values are included on purpose. With an "exactly k" constraint the DP must sometimes take a node with negative value, and the brute force confirms that it does.
Common Variations
The merge loop stays the same in each of these. Only the base case or the final read changes.
| Variation | Change |
|---|---|
| At most `k` nodes | Return `max(r[1:k+1])` instead of `r[k]` |
| Set need not contain the global root | Record `dp[u][k]` for every `u` once its table is final, and take the max |
| Each node has a cost, budget `W` | Index by cost: base case puts `value[u]` at index `cost[u]`, cap at `W` |
| Forest of prerequisite trees | Add a virtual root with value 0 connecting all roots, and ask for `k + 1` nodes |
| Count sets instead of maximizing | Replace `max` with `+` and `+` with `*`, all modulo a prime |
For the "need not contain the global root" variation, read each table at the moment it becomes final. That is the point just before the loop merges u into its parent. In the code above, that check goes right before dp[u] = None.
For the cost-indexed version, the bound changes. The next chapter's argument depends on table length being limited by subtree size. With arbitrary costs, a single node can fill a table of length W, and the total work becomes O(n·W²) in the worst case.
Pitfalls
Other mistakes to watch for:
- In-place merging. Writing
a[i + j] = max(a[i + j], a[i] + b[j])while still readingacan stack the same child twice. Either write into a fresh list, as above, or loopidownward the way 1D 0/1 knapsack does. - Using 0 for "impossible." If values can be zero or negative, 0 hides states that cannot be reached. Use
-infand skip those entries. Python floats handle-inf + xcorrectly, but thecontinueona[i] == NEGalso avoids wasted work. - Index 0 meaning "nothing chosen." In this state, the subtree's root is always chosen, so index 0 is impossible. If you change the state to allow the empty set, the "spend 0 in this child" case becomes
b[0] = 0. Then you must drop the copy ofaor you will double-count it. - Recursion depth. A path of 10⁵ nodes overflows Python's default recursion limit. The reversed pre-order loop avoids recursion entirely.
- Reading a table too early. A parent's table is final only after all its children are merged. In reversed pre-order, that happens when the loop reaches the parent itself, not when the loop reaches the parent's last child in some other ordering.
How Expensive Is This?
Each merge costs about len(a) × len(b), limited by k. A loose bound is O(n·k²): there are n - 1 merges and each costs at most k². The true total is O(n·k), and O(n²) when k = n. This holds only because the code limits both loops by the current table lengths and by k. The next chapter proves that bound. For this chapter, the rule to follow is: never loop past a table's real length.
Exercise
Using the example tree (edges (0,1), (0,2), (1,3), (1,4), (2,5) and values [1, 5, 4, 7, 3, 9]), compute the root's full table for k = 4 by hand. Which set achieves dp[0][4]?
Show answer
The root's table is [-, 1, 6, 14, 19]. Node 1's table is [-, 5, 12, 15] and node 2's table is [-, 4, 13]. Merging node 1 into the root gives [-, 1, 6, 13, 16]. Merging node 2 then gives index 4 = max(16, 6 + 13, 13 + 4) = 19, from 2 nodes in each branch: {0, 1, 3, 2, 5} would be 5 nodes, so the winning set is {0, 1, 2, 5} with 1 + 5 + 4 + 9 = 19.
Exercise
Modify bestrootedsubtree so that it returns the best value of a connected set of exactly k nodes anywhere in the tree, not necessarily containing node 0. Where exactly do you read each table?
Show answer
Keep a variable best = NEG. In the loop, read dp[u] right before it is merged into its parent, because every child of u has been merged by then: if k < len(dp[u]), set best = max(best, dp[u][k]). After the loop, also check the root's table. Return best, or None if it is still NEG. This works because every connected set has a unique highest node u, and dp[u][k] covers exactly the sets whose highest node is u.
Exercise
A student initializes every table as [NEG] * (k + 1) with dp[u][1] = value[u], and loops i and j over range(1, k + 1). The answers are correct. What is wrong, and what is the cost for n = 10^5 and k = 300?
Show answer
Every merge now costs about k² operations regardless of subtree size, so the total is O(n·k²), roughly 10^5 × 9 × 10^4 = 9 × 10^9 steps. That is far too slow. With size-bounded tables the total is O(n·k), about 3 × 10^7 steps.
Exercise
Why does the code copy a into merged before the double loop instead of starting merged as all NEG?
Show answer
The copy covers the option "spend zero nodes in this child's subtree." The child's table has no usable index 0, because its state requires the child itself to be chosen. Without the copy, every set counted for the parent would have to include the child, so a parent could never skip a child branch.