Compute Subtree Sums from Parent Array
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests bottom-up aggregation in trees represented as parent arrays, requiring iterative traversal to avoid recursion limits on deep trees.
You are given a tree with n nodes labeled from 0 to n - 1. The tree is represented as a parent array where parent[i] indicates the parent of node i, and each node has an integer value stored in values[i].
Your task is to calculate the subtree sum for each node. The subtree sum of a node is the total of all values in its subtree (the node itself plus all its descendants).
Return an array where the element at index i represents the subtree sum for node i.
Input Format
parent: A list of integers whereparent[i]is the parent node of nodei. The root node (node0) hasparent[0] = -1.values: A list of integers wherevalues[i]is the value stored at nodei.
Output Format
Return a list of integers where the i-th element is the sum of all values in the subtree rooted at node i.
Constraints
1 <= n == len(parent) == len(values) <= 10^5parent[0] == -1- For all
i >= 1:0 <= parent[i] < n - The parent array represents a valid tree (connected, acyclic, rooted at node
0) -10^4 <= values[i] <= 10^4- Parent indices may be larger than child indices
- The tree may form a single path of depth up to
n, so recursive solutions may exceed stack limits
Examples
Example 1
Input: compute_subtree_sums([-1, 0, 0, 1, 1, 3, 2], [5, 3, -2, 4, 1, 6, 7])
Output: [24, 14, 5, 10, 1, 6, 7]
Example 2
Input: compute_subtree_sums([-1, 2, 0, 1], [1, -1, 1, -1])
Output: [0, -2, -1, -1]
Example 3
Input: compute_subtree_sums([-1], [8])
Output: [8]
Hints
Hint 1
A node's subtree sum equals its own value plus the subtree sums of all its children
Hint 2
You need to process children before their parents - this is a post-order traversal
Hint 3
Use BFS from the root to establish a visiting order, then reverse it to get a valid bottom-up processing sequence
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The subtree sum for any node equals its own value plus the subtree sums of all its children:
result[u] = values[u] + sum(result[c] for each child c of u)
This naturally suggests a post-order traversal where we process children before parents. While recursion expresses this elegantly, the constraints allow trees with depth up to 10^5, which exceeds Python's default recursion limit and risks stack overflow.
The iterative solution works in three phases:
- Build adjacency lists: Convert the parent array into child lists so we can traverse the tree top-down
- Generate BFS order: Starting from the root, perform breadth-first traversal to create an ordering where every parent appears before all its children
- Accumulate bottom-up: Reverse the BFS order to get an ordering where children appear before parents. Initialize the result with the original values, then walk this reversed order, adding each node's computed sum into its parent
The key insight is that reversing BFS order gives us a valid post-order: when we process a node, all its descendants have already been processed and their subtree sums are complete.
Correctness
When we process node u in the reversed order:
- Every descendant of
uappears deeper in the tree - BFS visits nodes in non-decreasing depth order, so all descendants appear after
uin BFS order - Therefore, all descendants appear before
uin reversed BFS order - Each descendant has already added its complete subtree sum upward through the chain of parent links
- When
uadds its sum to its parent,result[u]containsvalues[u]plus all its children's subtree sums, which is exactly the definition ofu's subtree sum
Parent indices can exceed child indices (this is explicitly allowed), so we cannot simply iterate backwards by index. The processing order must respect tree structure, which BFS provides.
Complexity
Time: O(n). Building child lists visits each node once. BFS appends each node once. The accumulation pass performs one addition per node.
Space: O(n) for the child lists, BFS order array, and output array. No recursion stack is used regardless of tree depth.
Implementation
from typing import List
def compute_subtree_sums(parent: List[int], values: List[int]) -> List[int]:
n = len(parent)
# Build child lists for each node
children = [[] for _ in range(n)]
for i in range(1, n):
children[parent[i]].append(i)
# BFS order starting from root
order = [0]
for node in order:
order.extend(children[node])
# Initialize result with original values
result = list(values)
# Process in reverse BFS order (children before parents)
for node in reversed(order):
if parent[node] >= 0:
result[parent[node]] += result[node]
return result