Sub topic 6
Paths That Bend: Diameter and Maximum Path Sum
The DP problems so far gave every answer the same shape: a subtree's value was built from its children's values and passed up to its parent. Path problems break that pattern. The best path in a tree may climb up from one leaf, bend at some node, and go back down into a different branch. Such a path is never "owned" by a single child, so the DP has to keep track of two things: what a subtree can offer its parent, and what the subtree can achieve on its own.
This chapter assumes you know iterative DFS and Python, and that you have the root_tree helper from the earlier chapters. That helper returns parent, a pre-order order in which every parent comes before its children, and subtree sizes. Walking reversed(order) processes every node after all of its descendants.
The Shape of a Path in a Rooted Tree
Root the tree anywhere. Every simple path then has exactly one highest node, the node closest to the root. Call it the path's apex. Seen from the apex, the path is made of at most two downward branches, each going into a different child subtree. Either branch can be empty.
This gives a complete search plan. If we compute, for every node u, the best path whose apex is u, then the overall answer is the maximum over all u. Each such path is built from at most two downward branches out of u.
So every node needs two quantities:
| Quantity | Meaning | Passed to parent? |
|---|---|---|
| `down[u]` | Best path that starts at `u` and goes only downward | Yes, the parent can extend it by one edge |
| best through `u` | Best path whose apex is `u`, joining up to two branches | No, it bends, so it cannot be extended upward |
Getting this distinction right matters more than anything else in this chapter. A path that already bends at u cannot be extended to u's parent, because then u would have three path edges touching it. Only down[u] travels upward. The bent value goes into a global maximum.
Tree Diameter (Unweighted)
The diameter is the number of edges on the longest path in the tree. Let down[u] be the number of edges on the longest downward path from u. A leaf has down = 0, and for an internal node:
down[u] = max over children c of (down[c] + 1)- best path with apex
u= sum of the two largest values ofdown[c] + 1(with0used for a missing branch)
You could collect every child's down[c] + 1, sort the list, and add the top two. That works, but there is a simpler way. When a new child branch cand arrives at parent p, the best path through p that uses this branch pairs it with the best branch p has seen so far, and that best branch is the current down[p]. Then down[p] is updated. Because each pair of branches is compared once the later one arrives, the true top two always get combined.
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(3, [(0, 1), (1, 2)])) # 2
print(tree_diameter(4, [(0, 1), (0, 2), (0, 3)])) # 2
print(tree_diameter(6, [(0, 1), (1, 2), (1, 3), (3, 4), (4, 5)])) # 4
print(tree_diameter(1, [])) # 0Why the Incremental Combine Is Correct
When we process child u of p, down[u] is final. Every descendant of u comes after u in the pre-order, so in reverse it comes before u. However, down[p] is still partial and holds only the branches of p's children processed so far. That is exactly what we want. Take any two children c1 and c2 of p, where c2 is processed later. When c2 arrives, down[p] is at least down[c1] + 1, so the candidate down[p] + down[c2] + 1 is at least as long as the path that joins those two branches. A path that uses only one branch is covered too, because down[p] starts at 0.
The top-two method is equivalent. It is worth knowing because some problems need the top two (or top three) branches explicitly, for example when you have to know which child gave the best branch.
Watch the Units
The code counts edges. If a problem asks for the number of nodes on the longest path, add one at the end. Mixing the two is the most common off-by-one in diameter problems. Starting down at 1 for node counts also works, but then the combine step must subtract one so the apex is not counted twice.
Weighted Diameter
With edge weights, replace the + 1 with the weight of the edge from u to its parent. root_tree does not return edge weights, so we look them up.
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 weighted_diameter(n, wedges):
# wedges: list of (u, v, w) with w >= 0
parent, order, _ = root_tree(n, [(u, v) for u, v, _ in wedges], 0)
w_of = {}
for u, v, w in wedges:
w_of[(u, v)] = w
w_of[(v, u)] = w
down = [0] * n
best = 0
for u in reversed(order):
p = parent[u]
if p != -1:
cand = down[u] + w_of[(p, u)]
best = max(best, down[p] + cand)
down[p] = max(down[p], cand)
return best
print(weighted_diameter(4, [(0, 1, 3), (0, 2, 4), (2, 3, 5)])) # 12The longest path here is 1–0–2–3 with weight 3 + 4 + 5 = 12.
Maximum Path Sum with Node Weights
Now let every node carry a weight, which may be negative, and ask for the largest sum of weights along any non-empty path. This is the tree form of a well-known interview problem, which is usually stated for binary trees but works the same way on any tree.
Two changes are needed compared with the diameter:
- A branch is optional. If the best downward path from a child has a negative sum, the apex should ignore that child. So each child contributes
gain = max(0, down[c]). - The path must contain at least one node. If every weight is negative, the answer is the largest single weight, not 0.
Now down[u] means the best sum of a downward path that starts at u and includes u. It starts as weight[u], and it grows when a child offers a positive gain.
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 max_path_sum(n, edges, weight):
parent, order, _ = root_tree(n, edges, 0)
down = list(weight) # best downward path starting at u, including u
best = max(weight) # a single node is a valid path
for u in reversed(order):
p = parent[u]
if p != -1:
gain = max(0, down[u])
best = max(best, down[p] + gain)
down[p] = max(down[p], weight[p] + gain)
return best
# 0 is the root with children 1 and 2; node 2 has children 3 and 4
print(max_path_sum(5, [(0, 1), (0, 2), (2, 3), (2, 4)], [-10, 9, 20, 15, 7])) # 42
print(max_path_sum(2, [(0, 1)], [-3, -1])) # -1In the first example, the path 3–2–4 bends at node 2 and sums to 15 + 20 + 7 = 42. It never reaches the root. Node 2 offers only down[2] = 35 (the 2–3 branch) to its parent. The root's best is then −10 + 35 = 25, which is smaller.
Trace of the Combine Step
The reverse order for this tree is 1, 3, 4, 2, 0.
| Child `u` | Parent `p` | `gain` | Candidate `down[p] + gain` | `best` after | `down[p]` after |
|---|---|---|---|---|---|
| 1 | 0 | 9 | −10 + 9 = −1 | 20 | −1 |
| 3 | 2 | 15 | 20 + 15 = 35 | 35 | 35 |
| 4 | 2 | 7 | 35 + 7 = 42 | 42 | 35 |
| 2 | 0 | 35 | −1 + 35 = 34 | 42 | 25 |
Look at the row for child 4. down[2] already holds 20 + 15, so adding 7 joins both branches through the apex in one step.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Returning `down[root]` | Wrong when the best path bends below the root | Keep a global `best` updated at every node |
| Passing the bent value upward | Paths with three edges at a node, answers too large | Only `down[u]` goes to the parent |
| Initializing `best = 0` with negative weights | Returns 0 when all weights are negative | Start from `max(weight)` |
| Forgetting to clamp negative branches | Answer too small; apex forced to take bad branches | Use `max(0, down[c])` |
| Edges vs nodes confusion | Off by one | Decide the unit up front and convert at the end |
| Recursive DFS on a path-shaped tree | `RecursionError` near depth 1000 | Use the iterative `order` as shown |
| Calling with `n = 0` | `root_tree` indexes an empty list | Handle the empty tree before the DP |
Comparison: The Two-Search Trick
For diameter with non-negative weights there is a well-known alternative. Run a DFS or BFS from any node to find the farthest node a. Then run another search from a to find the farthest node b. The distance from a to b is the diameter.
| Method | Passes | Handles negative weights | Generalizes to other path objectives |
|---|---|---|---|
| Two farthest-node searches | 2 | No | No |
| DP with apex combining | 1 | Yes, with clamping | Yes |
The two-search trick relies on a property of farthest points that fails as soon as an edge can be negative. Use the DP whenever weights can be negative, nodes carry values, or the objective is anything other than plain length. The same apex idea also handles longest paths under constraints, counting pairs at distance k with a per-node depth table, and the rerooting technique in a later chapter, which reuses the top-two-branches information.
Recovering the Path Itself
Sometimes you need the endpoints, not just the length. Store, for each node, via[u], the child that produced down[u] (or -1 if the branch stops at u). Whenever best improves at parent p while processing child u, record the apex p, the new branch child u, and the current via[p] (the previous best branch). After the pass, walk down via from each recorded child to a leaf, and join the two walks at the apex. This adds O(n) memory and no extra passes.
Exercise
A tree has 7 nodes and edges (0,1), (0,2), (1,3), (1,4), (4,5), (5,6). Using tree_diameter rooted at 0, what is the diameter, and which node is the apex of the longest path?
Show answer
The diameter is 4 edges, along the path 3–1–4–5–6. Its apex is node 1: one branch goes to 3 (length 1) and the other goes through 4 and 5 to 6 (length 3). The path 2–0–1–4–5–6 has 5 edges, though, so the true diameter is 5 with apex 0: branch 0–2 has length 1 and branch 0–1–4–5–6 has length 4. The DP finds 5 because it checks every node as an apex.
Exercise
In maxpathsum, why does the update use down[p] = max(down[p], weight[p] + gain) instead of down[p] = down[p] + gain?
Show answer
down[p] must describe a downward path, which uses at most one child branch. Adding every gain would merge several branches into a shape that is no longer a path. Taking the max of weight[p] + gain over children keeps only the best single branch. The two-branch combination is counted only in best.
Exercise
Modify tree_diameter so it returns the number of nodes on the longest path instead of the number of edges. What is the smallest change, and what does it return for a single-node tree?
Show answer
Return best + 1. A path with e edges has e + 1 nodes, and the DP's edge count is otherwise correct. For a single-node tree best is 0, so the result is 1.
Exercise
Edge weights may now be negative. Adapt weighted_diameter to return the maximum-weight path, where a path with no edges (a single node) has weight 0.
Show answer
Clamp each branch before using it: compute cand = max(0, down[u] + w_of[(p, u)]), then best = max(best, down[p] + cand) and down[p] = max(down[p], cand). Since down starts at 0 and every cand is at least 0, a negative branch is never used, and best stays at least 0, which is the single-node path.