KatInterview

Calculate Subtree Totals in a Tree

Trees & GraphsAuto-graded · 23 test cases
HardAuto-gradedTrees & Graphstrees-graphsdfstree-traversal

Last 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$
  • edges contains exactly $n - 1$ pairs of node labels [u, v].
  • $1 \le u, v \le n$
  • val is 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.