Sub topic 4
Warm-up: Subtree Sizes and Sums
This chapter assumes you can read Python, know what an adjacency list is, and have seen the root_tree helper from the previous chapter. That helper roots the tree and returns a parent array, an order list in which every parent appears before its children, and the subtree sizes. Here we look closely at the simplest kind of tree DP: aggregates. An aggregate is a single number per subtree, such as its node count, the sum of its values, or its height, computed by folding each child's number into its parent's.
Aggregates matter for two reasons. They are often the answer to a problem, or a direct step toward it. They are also the building blocks for later techniques: rerooting needs subtree sizes, tree knapsack needs sizes to bound its work, and small-to-large merging needs sizes to decide which side is "small". If you get the mechanics right here, the later chapters only change what each node stores.
The Working Model
Every aggregate in this chapter has three parts:
- Initial value at a node. This is the answer for a subtree that contains only that node. For size it is 1, for a sum it is the node's own value, and for height it is 0.
- Combine step. This folds one finished child's result into the parent's running result. For size and sum it is addition. For height it is
max(height[p], height[u] + 1). - Order. A node's result is final once all of its children have been folded in. Walking
reversed(order)guarantees this.
The combine step must be associative and commutative, or at least not depend on the order in which children arrive. Addition and max both qualify. That is why we can fold children in one at a time, in whatever order the traversal produces, without first collecting a list of children.
Why reversed order is enough
The iterative DFS from the previous chapter appends a node to order when it is popped. A child is pushed only while its parent is being popped, so the child is popped, and appended, later than the parent. Every node therefore appears after its parent in order. By induction, it also appears after every ancestor.
Reverse the list and every node now comes before all of its ancestors. When the loop reaches node u, every descendant of u has already been visited. Each of those descendants pushed its result into its own parent at that moment, so all contributions inside u's subtree have already been added up into u. Then u pushes its finished value into parent[u].
You do not need a true post-order, where each subtree sits in one contiguous block. You only need every descendant to come before its ancestor. Reversed pre-order gives you that.
A Worked Example
We will use this tree with 7 nodes, rooted at 0, and these node values:
| Node | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Value | 5 | 3 | -2 | 4 | 1 | 7 | 6 |
With edges listed as (0,1), (0,2), (1,3), (1,4), (2,5), (5,6), the stack-based DFS produces order = [0, 2, 5, 6, 1, 4, 3]. Reversed, that is 3, 4, 1, 6, 5, 2, 0. Check the property: 3 and 4 come before 1, 6 comes before 5, 5 before 2, and everything before 0.
Here is how each step updates the parent's running values for size and sum:
| Step | Node `u` | `parent[u]` | Parent size after | Parent sum after |
|---|---|---|---|---|
| 1 | 3 | 1 | 1 + 1 = 2 | 3 + 4 = 7 |
| 2 | 4 | 1 | 2 + 1 = 3 | 7 + 1 = 8 |
| 3 | 1 | 0 | 1 + 3 = 4 | 5 + 8 = 13 |
| 4 | 6 | 5 | 1 + 1 = 2 | 7 + 6 = 13 |
| 5 | 5 | 2 | 1 + 2 = 3 | -2 + 13 = 11 |
| 6 | 2 | 0 | 4 + 3 = 7 | 13 + 11 = 24 |
| 7 | 0 | none | final 7 | final 24 |
At step 3, node 1 pushes its sum of 8 into node 0. That is only correct because both of node 1's children were already folded in at steps 1 and 2. The root ends with size 7 and sum 24. Those numbers equal n and the sum of all values, which makes a cheap sanity check.
The Code
The script below is self-contained. It repeats root_tree so you can run it directly.
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 subtree_aggregates(n, edges, value, root=0):
parent, order, size = root_tree(n, edges, root)
# Bottom-up: children before parents.
total = list(value) # sum of values in u's subtree
height = [0] * n # longest downward path from u, in edges
for u in reversed(order):
p = parent[u]
if p != -1:
total[p] += total[u]
height[p] = max(height[p], height[u] + 1)
# Top-down: parents before children.
depth = [0] * n # edges from the root to u
for u in order:
p = parent[u]
if p != -1:
depth[u] = depth[p] + 1
return parent, order, size, total, height, depth
def all_pairs_distance_sum(n, edges):
# Each edge (parent[u], u) lies on the path between every node
# inside u's subtree and every node outside it.
parent, _, size = root_tree(n, edges, 0)
return sum(size[u] * (n - size[u]) for u in range(n) if parent[u] != -1)
if __name__ == "__main__":
n = 7
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (5, 6)]
value = [5, 3, -2, 4, 1, 7, 6]
parent, order, size, total, height, depth = subtree_aggregates(n, edges, value)
print("order ", order)
print("size ", size)
print("total ", total)
print("height", height)
print("depth ", depth)
print("pair distance sum", all_pairs_distance_sum(n, edges))Running it prints:
order [0, 2, 5, 6, 1, 4, 3]
size [7, 3, 3, 1, 1, 2, 1]
total [24, 8, 11, 4, 1, 13, 6]
height [3, 1, 2, 0, 0, 1, 0]
depth [0, 1, 1, 2, 2, 2, 3]
pair distance sum 52Bottom-up versus top-down
size, total, and height describe what lies below a node, so information flows up and the loop runs over reversed(order). depth describes the path above a node, so information flows down and the loop runs over order itself. The parent's depth must be final before the child reads it, and forward order guarantees that.
This split comes back in the rerooting chapter. There, a bottom-up pass computes subtree answers and a top-down pass spreads the answer for the whole tree from each parent to its children.
Push style versus pull style
The code above uses push style: when u is finished, it adds itself into parent[u]. The other option is pull style: when u is processed, it loops over its children and reads their values.
def subtree_sums_pull(n, edges, value, root=0):
parent, order, _ = root_tree(n, edges, root)
children = [[] for _ in range(n)]
for u in range(n):
if parent[u] != -1:
children[parent[u]].append(u)
total = [0] * n
for u in reversed(order):
total[u] = value[u] + sum(total[c] for c in children[u])
return total
print(subtree_sums_pull(7, [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (5, 6)],
[5, 3, -2, 4, 1, 7, 6]))
# [24, 8, 11, 4, 1, 13, 6]Both styles run in O(n), because each edge is used once. Push style needs no children lists and fits a fold that handles one child at a time. Pull style is clearer when the transition needs all the children together, for example to find the two largest children, or when you want the node's whole computation in one place. Later chapters mostly use push style. Choose whichever makes the transition easier to read.
An Application: Every Pairwise Distance at Once
all_pairs_distance_sum shows why subtree sizes are worth computing. We want the sum of the distances between all pairs of nodes. Checking every pair with BFS would take O(n²). Count by edge instead. Removing the edge between u and parent[u] splits the tree into u's subtree, with size[u] nodes, and everything else, with n - size[u] nodes. A path crosses this edge exactly when its two endpoints lie on opposite sides. So the edge contributes size[u] * (n - size[u]) to the total.
For the example, the edges above nodes 1 through 6 contribute 12, 12, 6, 6, 10, and 6, for a total of 52. Computing the sum of distances from each node separately and halving the grand total gives the same 52.
This contribution technique, which asks how many answers use a given edge or node, turns many quadratic counting problems into a single pass over sizes. It is worth trying whenever a problem sums something over all pairs or all paths.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Looping over `order` instead of `reversed(order)` for a bottom-up value | A parent reads a child's value before that child has finished, so sizes come out too small | Bottom-up uses `reversed(order)`, top-down uses `order` |
| Initializing `size` to 0 | Every size is one too small and leaves report 0 | The initial value describes a one-node subtree, so it is 1 |
| Initializing a max-type aggregate to 0 when values can be negative | A subtree "maximum value" of 0 even though every value is negative | Start from the node's own value, or from `float('-inf')` |
| Recursive DFS on deep trees | `RecursionError`, or a crash on a path of 10⁵ or more nodes | Use the iterative order, or see the callout below |
| Reusing arrays across test cases | Values from the previous test leak into the next one | Allocate fresh arrays inside the function |
| Assuming the input is connected | Nodes never reached by the DFS keep their initial values without any error | Check `len(order) == n`, or root each component separately |
| Treating the stack order as a contiguous post-order | Range queries over subtrees go wrong | This order only guarantees ancestor-before-descendant. Use an explicit Euler tour if you need contiguous ranges |
Edge cases worth testing
- n = 1, no edges.
order == [0], the loops do nothing, and every aggregate equals its initial value. - A path 0–1–2–…–(n−1). This is the deepest possible tree and the case that breaks recursion.
height[0] == n - 1. - A star. One node has n − 1 children, and every other node is a leaf. Push style handles it without any special code.
- A different root. Sizes and sums change with the root, but
total[root]andsize[root]do not. The pairwise distance sum does not depend on the root either, which makes a good property test.
Exercises
Exercise
Change subtree_aggregates so it also returns leaves[u], the number of leaves in u's subtree. A leaf is a non-root node with no children. What are the initial value and the combine step, and what is leaves for the example tree?
Show answer
Use pull logic for the initial value, or detect leaves after the pass: set leaves[u] = 0 for every u, then in the reversed(order) loop, when u is reached and leaves[u] is still 0 and u is not the root, set leaves[u] = 1, then add leaves[u] into leaves[parent[u]]. All of u's children have already pushed into u by then, so leaves[u] == 0 means u has no children. The combine step is addition. For the example, the leaves are 3, 4, and 6, so leaves = [3, 2, 1, 1, 1, 1, 1].
Exercise
Suppose you compute sizes by looping over order (forward) instead of reversed(order), still doing size[parent[u]] += size[u] starting from all ones. What does the root's size become for the example tree, and why?
Show answer
Forward order is [0, 2, 5, 6, 1, 4, 3]. Node 2 pushes into 0 while its size is still 1, giving size[0] = 2. Node 5 pushes 1 into node 2, but node 2 has already pushed. Node 1 pushes 1 into node 0, giving size[0] = 3. Each node pushes before its children have arrived, so the root only counts itself and its direct children. The result is 3 instead of 7.
Exercise
Using only size and parent, find an edge whose removal makes the larger of the two parts as small as possible. Give the O(n) rule and apply it to the example tree.
Show answer
Removing the edge above u leaves parts of size size[u] and n - size[u]. Choose the u, other than the root, that minimizes max(size[u], n - size[u]). For the example with n = 7, the edges above nodes 1 and 2 both give max(3, 4) = 4. Node 5 gives max(2, 5) = 5, and the leaves give 6. So cutting edge (0,1) or edge (0,2) is optimal, with a larger part of 4 nodes.
Exercise
Write a top-down pass that computes root_sum[u], the sum of values on the path from the root to u including both ends. What is it for node 6 in the example?
Show answer
Set root_sum[root] = value[root], then for u in order with p = parent[u] != -1, set root_sum[u] = root_sum[p] + value[u]. Forward order works because the parent's value is final before the child reads it. For node 6 the path is 0, 2, 5, 6, so the sum is 5 + (-2) + 7 + 6 = 16.