Calculate Subtree Totals in a Tree
Trees & GraphsAuto-graded · 23 test casesLast updated
Given an undirected tree and node weights, compute the sum of values for every subtree rooted at node 1.
You are given an unrooted, connected graph with $n$ nodes labeled from $1$ to $n$ and $n-1$ undirected edges (forming a tree). Node $1$ is designated as the root of the tree.
Each node $i$ ($1 \le i \le n$) has a numerical value assigned to it, given in a 0-indexed array val where node $i$ has value val[i - 1].
The subtree of a node $u$ consists of $u$ itself along with all of its descendants (nodes whose path to root $1$ passes through $u$).
Write a function to return an array of length $n$, where the $i$-th element (0-indexed) is the total sum of node values in the subtree of node $i + 1$.
Constraints
- $1 \le n \le 200,000$
edgescontains exactly $n - 1$ pairs of node labels[u, v].- $1 \le u, v \le n$
valis a list of length $n$.- $-10^9 \le \text{val}[i] \le 10^9$
Examples
Example 1
Input: compute_subtree_sums(5, [[1, 2], [1, 3], [3, 4], [3, 5]], [1, 2, 3, 4, 5])
Output: [15, 2, 12, 4, 5]
Example 2
Input: compute_subtree_sums(3, [[1, 2], [2, 3]], [-1, 2, -3])
Output: [-2, -1, -3]
Example 3
Input: compute_subtree_sums(1, [], [7])
Output: [7]
Hints
Hint 1
The subtree sum of a node is equal to its own value plus the subtree sums of all its children.
Hint 2
Since computing a node's total requires its children's totals to be ready first, process the tree bottom-up (post-order).
Hint 3
To handle deep trees (up to 200,000 nodes) without exceeding Python's default stack recursion limit, collect a topological or level-by-level traversal order iteratively, then process it in reverse.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks us to find the total sum of node values within the subtree of every node $u$ when the tree is rooted at node $1$.
A node's total subtree sum can be defined recursively as: $$\text{subtree_sum}[u] = \text{val}[u - 1] + \sum_{c \in \text{children}(u)} \text{subtree_sum}[c]$$
Because a parent's sum depends on its children's sums, we must aggregate information from the bottom up (a post-order evaluation).
Avoiding Stack Overflow
While standard recursion using DFS works conceptually, $n$ can be as large as $200,000$. A deep linear tree would require $200,000$ nested recursive calls, which exceeds the default recursion stack limit in Python.
To solve this iteratively:
- Top-Down Pass (Tree Structuring): Perform an iterative BFS starting from root node $1$. Track each node's direct parent and maintain a list
orderrecording nodes as they are visited. Since parents are processed before their children, every parent inorderprecedes its descendants. - Bottom-Up Accumulation: Initialize
subtree_sum[u]toval[u - 1]. Iterate throughorderin reverse. By processing nodes in reverse traversal order, every child is processed before its parent. We add each node's computed subtree sum directly into its parent's accumulator.
Complexity Analysis
- Time Complexity: $\mathcal{O}(n)$. Constructing the adjacency list takes $\mathcal{O}(n)$ time. Building the traversal order inspects each edge twice, taking $\mathcal{O}(n)$ time. Reversing the order and propagating subtree sums takes $\mathcal{O}(n)$ time.
- Space Complexity: $\mathcal{O}(n)$. We store the graph adjacency list,
parentlinks, traversalorder, and the result array. No stack frame memory is consumed.
Python 3 Source Code
from typing import List
def compute_subtree_sums(n: int, edges: List[List[int]], val: List[int]) -> List[int]:
adj = [[] for _ in range(n + 1)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [0] * (n + 1)
parent[1] = -1
order = [1]
# Iterative BFS to establish parent relationships and topological ordering
for u in order:
for v in adj[u]:
if v != parent[u]:
parent[v] = u
order.append(v)
# Initialize each subtree sum with its own value
subtree_sum = [0] * (n + 1)
for u in range(1, n + 1):
subtree_sum[u] = val[u - 1]
# Propagate sums bottom-up
for u in reversed(order):
if parent[u] > 0:
subtree_sum[parent[u]] += subtree_sum[u]
return subtree_sum[1:]