Sub topic 8
Rerooting: Every Node as the Root in Linear Time
This chapter assumes you can root a tree with an iterative DFS, compute subtree sizes in post-order, and write a bottom-up transition from child states. It builds on the root_tree helper and the subtree aggregates from earlier chapters.
The Problem: One Answer per Root
Many tree questions ask for a value at every node. A common one: for each node v, find the sum of distances from v to all other nodes. You could run a BFS from each node, but that costs O(n) per node and O(n²) in total. With n = 200,000 that is far too slow.
Rerooting fixes this with two passes:
- A bottom-up pass computes the full answer for one root, usually node 0.
- A top-down pass moves the root across one edge at a time. Each move updates the answer in O(1).
The method works because moving the root from a parent p to its child u changes only a few things you can predict.
What Changes When the Root Moves
Root the tree at 0 and let size[u] be the number of nodes in u's subtree. Suppose you already know ans[p], the sum of distances from p. Now stand at u instead.
- The
size[u]nodes insideu's subtree are each one step closer. - The other
n - size[u]nodes are each one step farther.
That gives the transition:
ans[u] = ans[p] - size[u] + (n - size[u])
The Bottom-Up Pass
To get ans[0], define down[u] as the sum of distances from u to the nodes in its own subtree. A child c adds down[c], plus 1 for each of the size[c] nodes under it, because every one of those paths uses the edge u–c:
down[u] = sum over children c of (down[c] + size[c])
At the root, down[0] covers every node, so ans[0] = down[0].
Full Implementation
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 sum_of_distances(n, edges):
parent, order, size = root_tree(n, edges, 0)
down = [0] * n # sum of distances from u to nodes in its subtree
for u in reversed(order):
p = parent[u]
if p != -1:
down[p] += down[u] + size[u]
ans = [0] * n
ans[0] = down[0]
for u in order:
p = parent[u]
if p != -1:
ans[u] = ans[p] - size[u] + (n - size[u])
return ans
edges = [(0, 1), (0, 2), (2, 3), (2, 4)]
print(sum_of_distances(5, edges)) # [6, 9, 5, 8, 8]The two passes walk the same order list in opposite directions. Reversed, it puts children before parents, which the bottom-up pass needs. Forward, it puts parents before children, so ans[p] is always ready before ans[u] reads it.
Worked Example
For the edges above, rooted at 0:
| Node | size | down | ans |
|---|---|---|---|
| 0 | 5 | 6 | 6 |
| 1 | 1 | 0 | 6 − 1 + 4 = 9 |
| 2 | 3 | 2 | 6 − 3 + 2 = 5 |
| 3 | 1 | 0 | 5 − 1 + 4 = 8 |
| 4 | 1 | 0 | 5 − 1 + 4 = 8 |
A direct check from node 2: distances are 1 to node 0, 2 to node 1, 1 to node 3, and 1 to node 4, for a total of 5.
Common Errors
- Running the top-down pass in the wrong order. If you iterate
reversed(order)the second time, you readans[p]before anyone has set it. - Using recursion. A path-shaped tree of 10⁵ nodes overflows Python's default recursion limit. Both passes here are plain loops.
- Assuming every combine can be undone. The sum transition subtracts a child's contribution from its parent. Max and min cannot be subtracted. For a problem like "farthest node from each vertex", store each node's best and second-best child values, or build prefix and suffix maxima over its children. Then you can exclude one child without recomputing the rest.
- Forgetting the "up" part in general rerooting. In harder problems you compute
up[u], the answer contributed by everything outsideu's subtree, and combine it withdown[u]. The distance-sum formula hides this step becauseans[p]already contains it.
Exercise
Each edge now has a positive weight w. How does the top-down transition for sum of distances change when the root moves from p to its child u across an edge of weight w?
Show answer
The size[u] nodes in u's subtree each get w closer and the other n - size[u] nodes each get w farther, so ans[u] = ans[p] + w (n - 2 size[u]). The bottom-up pass also changes: down[p] += down[u] + w * size[u].
Exercise
You want, for every node, the distance to the farthest node (its eccentricity). Why can't you get the parent's value excluding child u by subtracting u's contribution, and what do you store instead?
Show answer
The combine is max, and you cannot undo a max by subtraction. If u gave the parent's best branch, the next-best branch is lost. Store the top two downward depths at each node (or prefix and suffix maxima over the children). When moving to u, use the second-best branch whenever the best one came through u.