Build a Tree Whose Nodes Hold the Original Tree's Subtree Sums
SnowflakeSoftware Engineer · Technical ScreenLast updated
Given a rooted tree as a parent array with a value on every node, return a same-shaped tree whose nodes hold the sum of each original subtree. It tests aggregating children before parents without hitting recursion limits, and leaving the original tree unchanged.
Every node of a rooted tree holds an integer. Build a second tree with the same shape in which each node holds the sum of all the values in the corresponding subtree of the original tree, leaving the original tree as it is. The new tree has the same parent links as the original, so return only its values.
Function Signature
def subtree_sum_tree(parent: list[int], values: list[int]) -> list[int]:
Rules
- The tree has
nnodes numbered0ton - 1. Node0is the root andparent[0] == -1. For every other nodei,parent[i]is the index of its parent. A node can have any number of children, and parents can have larger indices than their children. values[i]is the value held by nodeiin the original tree.- The subtree of a node consists of the node and all of its descendants.
- Return a list
sumsof lengthnin whichsums[i]is the total ofvalues[j]over every nodejin the subtree of nodei. Together withparent,sumsdescribes the new tree.
Constraints
1 <= n == len(parent) == len(values) <= 10^5parent[0] == -1, and fori >= 1,0 <= parent[i] <= n - 1; the parent links form a single tree rooted at node0with no cycles.-10^4 <= values[i] <= 10^4, so every sum lies between-10^9and10^9.- The tree can be a single path, so its depth can reach
n.
Examples
Example 1
0
/ \
1 2
/ \ \
3 4 6
|
5
Input: parent = [-1, 0, 0, 1, 1, 3, 2], values = [5, 3, -2, 4, 1, 6, 7]
Output: [24, 14, 5, 10, 1, 6, 7]
The drawing shows node indices. Node 3's subtree holds nodes 3 and 5, so its sum is 4 + 6 = 10. Node 1's subtree holds nodes 1, 3, 4 and 5: 3 + 4 + 1 + 6 = 14. Node 2's sum is -2 + 7 = 5, and the root's is 5 + 14 + 5 = 24. Leaves keep their own values.
Example 2
Input: parent = [-1, 2, 0, 1], values = [1, -1, 1, -1]
Output: [0, -2, -1, -1]
The tree is the path 0, 2, 1, 3. Node 1's subtree holds nodes 1 and 3 (sum -2), node 2's holds nodes 2, 1 and 3 (sum -1), and the root's holds all four nodes (sum 0).
Example 3
Input: parent = [-1], values = [8]
Output: [8]
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.