KatInterview

Compute Subtree Sums from Parent Array

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphstreespost-orderaggregation

Last 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 where parent[i] is the parent node of node i. The root node (node 0) has parent[0] = -1.
  • values: A list of integers where values[i] is the value stored at node i.

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^5
  • parent[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