Maximum Path Gain in a Weighted Tree
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests tree DP on a weighted tree to find the maximum sum of node values along any root-to-leaf path, using depth-first traversal and subproblem combination.
Maximum Path Gain in a Weighted Tree
You are given a weighted, rooted tree with n nodes numbered 0 to n-1. Node 0 is always the root.
The tree is described by a list of edges, where each edge is [u, v, w] meaning there is an undirected edge between node u and node v with integer weight w.
Your task is to find the maximum total weight along any root-to-leaf path.
A root-to-leaf path starts at node 0 and ends at a node that has no children (i.e., a leaf). The total weight of a path is the sum of all edge weights along that path.
Return the maximum such sum. If the tree has only the root and no edges (a single node), return 0.
Definitions:
- A leaf is any node with degree 1 in the tree except the root (node 0), even if the root itself has degree 1 (i.e., the root is never considered a leaf unless
n == 1). - When
n == 1, there are no edges and the only path is the trivial root-only path with sum0.
Constraints
1 ≤ n ≤ 2000edgeshas exactlyn - 1entries (the graph is always a valid tree).- Each edge is
[u, v, w]where0 ≤ u, v ≤ n-1and-1000 ≤ w ≤ 1000. - The graph is connected.
- Weights may be negative.
Examples
Example 1
Input: max_root_to_leaf_gain(1, [])
Output: 0
Example 2
Input: max_root_to_leaf_gain(4, [[0, 1, 3], [1, 2, 1], [1, 3, -2]])
Output: 4
Example 3
Input: max_root_to_leaf_gain(6, [[0, 1, 5], [0, 2, 2], [2, 3, 4], [2, 4, -1], [1, 5, 3]])
Output: 8
Hints
Hint 1
Build an adjacency list from the edge list, then do a DFS from node 0 keeping track of the parent to avoid revisiting.
Hint 2
At each node, if it is a leaf (no unvisited children), its contribution to the answer is the accumulated path sum so far.
Hint 3
Use a recursive DFS where the return value is the maximum root-to-leaf sum in the subtree rooted at that node; combine children results by taking the max.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This problem is a classic application of tree DP. We define:
dp[v]= the maximum sum of edge weights on any path from nodevdown to a leaf inv's subtree.
The recurrence is:
- If
vis a leaf:dp[v] = 0(no further edges to traverse). - If
vis an internal node:dp[v] = max over all children c of (weight(v→c) + dp[c]).
The answer is dp[0].
Why It Is Correct
Every root-to-leaf path passes through the root. At each node we independently choose the best child, which is optimal by the principle of optimal substructure: the best overall path through node v is the edge to the best child plus the best path within that child's subtree.
Implementation Notes
- We build an adjacency list and perform a post-order DFS from node 0 (tracking parents to distinguish children from the parent direction).
- Processing nodes in reverse DFS-discovery order (post-order) ensures every child's
dpvalue is ready before its parent's is computed. - An iterative DFS avoids Python's recursion limit for large inputs.
Edge Cases
n = 1: no edges, return0.- All negative weights: we still return the maximum (least negative) root-to-leaf sum — we cannot avoid all edges if we must reach a leaf.
- A path of length 1 (root has one child that is a leaf): correctly returns the single edge weight.
Complexity
| Time | O(n) — each node and edge visited once |
| Space | O(n) — adjacency list, parent arrays, dp array, and DFS stack |
Reference Solution
from typing import List
from collections import defaultdict
def max_root_to_leaf_gain(n: int, edges: List[List[int]]) -> int:
if n == 1:
return 0
# Build adjacency list: adj[u] = list of (v, w)
adj = defaultdict(list)
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
# Tree DP via iterative DFS (avoids recursion limit for n up to 2000)
parent = [-1] * n
parent_weight = [0] * n
order = [] # post-order discovery
visited = [False] * n
stack = [0]
visited[0] = True
while stack:
node = stack.pop()
order.append(node)
for nbr, w in adj[node]:
if not visited[nbr]:
visited[nbr] = True
parent[nbr] = node
parent_weight[nbr] = w
stack.append(nbr)
# Process in reverse discovery order (leaves before parents)
dp = [0] * n
for node in reversed(order):
children = [nbr for nbr, _ in adj[node] if parent[nbr] == node]
if not children:
dp[node] = 0 # leaf
else:
dp[node] = max(parent_weight[child] + dp[child] for child in children)
return dp[0]