Sub topic 6
Paths That Bend: Diameter and Maximum Path Sum
This chapter assumes you already know the root_tree helper from earlier chapters, which returns parent, a pre-order order, and size. It also assumes you know that walking reversed(order) finishes every child before its parent. You should be comfortable writing a transition from child states to a parent state.
Until now, every answer for a subtree has been something that gets passed up to the parent. Path problems are different. In a rooted tree, the best path may climb up from one leaf to some node and then go back down into a different branch. That path is never passed upward as a whole. You have to catch it at the node where it bends.
Two quantities per node
The fix is to keep two separate quantities:
| Quantity | Meaning | Passed to parent? |
|---|---|---|
| `down[u]` | Best path that starts at `u` and goes only downward | Yes |
| `best` | Best path seen anywhere, bending at some node | No, it is a global answer |
The value passed upward has to be a single chain, because the parent can only extend a path that has one free end. A path that bends at u already uses both of its ends, so it can only be recorded in the global answer.
Diameter
The diameter of a tree is the number of edges on its longest path. Here down[u] is the length in edges of the longest downward path from u. Each child u offers its parent a branch of length down[u] + 1. Before that branch is folded into down[p], it is joined with the best branch p has seen so far:
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_diameter(n, edges):
parent, order, _ = root_tree(n, edges, 0)
down = [0] * n # longest downward path from u, in edges
best = 0
for u in reversed(order):
p = parent[u]
if p != -1:
cand = down[u] + 1
best = max(best, down[p] + cand)
down[p] = max(down[p], cand)
return best
print(tree_diameter(5, [(0, 1), (1, 2), (1, 3), (3, 4)])) # 3This avoids sorting the children. When a new child branch arrives, down[p] already holds the deepest branch among the children processed so far. So down[p] + cand pairs the new branch with the best earlier one, and every pair of branches gets a chance to be the top two. A node with a single child gives 0 + cand, which covers paths that end at p.
Maximum path sum with node values
Now give each node a value, which may be negative, and find the path (at least one node) with the largest total. The structure stays the same, with one change: a branch with a negative total should be cut off rather than extended. Clamping each branch at zero handles this.
def max_path_sum(n, edges, value):
parent, order, _ = root_tree(n, edges, 0)
top = [0] * n # best non-negative child branch seen so far
best = max(value) # a single node is a valid path
for u in reversed(order):
down_u = value[u] + top[u] # all children of u are done
p = parent[u]
if p != -1:
cand = max(down_u, 0)
best = max(best, value[p] + top[p] + cand)
top[p] = max(top[p], cand)
return best
print(max_path_sum(3, [(0, 1), (1, 2)], [-1, 5, 3])) # 8
print(max_path_sum(2, [(0, 1)], [-4, -2])) # -2down_u is computed when u itself is reached in the reversed order. By that point, every child of u has already pushed its branch into top[u].
Common errors
- Returning
down[root]. That value only counts paths that start at the root. The answer lives inbest. - Updating before combining. If you write
down[p] = max(down[p], cand)before computingdown[p] + cand, the same branch can be counted twice, and a star with one long arm reports double its length. - Starting
bestat 0 with negative values. If every value is negative, the correct answer is the largest single value. Startingbestatmax(value)handles this. - Forgetting to clamp. Without
max(down_u, 0), a negative branch drags down every path that extends it. - Recursion. A path-shaped tree with 10⁵ nodes overflows Python's default recursion limit. The iterative
orderavoids recursion entirely.
Exercise
In tree_diameter, swap the two lines inside the loop so that down[p] is updated before best. What does the function return for the star with edges [(0, 1), (0, 2), (0, 3)], and why is that wrong?
Show answer
It returns 2 for a different reason. Take the first child processed. down[0] becomes 1, then best = down[0] + cand = 1 + 1 = 2, so that one branch is paired with itself. The true diameter is also 2 here, so the bug stays hidden. For the path [(0, 1)], the swapped version returns 2 instead of 1, which exposes the double counting.
Exercise
How would you change maxpathsum to also allow the empty path, with value 0?
Show answer
Initialize best = max(0, max(value)). Equivalently, return max(best, 0). Nothing else needs to change, because the branches are already clamped at zero.