Subtree Sum Replacement in Level-Order Arrays
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests post-order traversal, heap indexing in complete binary trees, and efficient bottom-up aggregation without recursion.
You are given two complete binary trees represented as level-order arrays tree1 and tree2. Both arrays have the same length and therefore describe trees with identical structure.
Your task is to compute a new level-order array where each position contains the sum of all values in the corresponding subtree of tree1. A subtree rooted at index i includes the node at i plus all its descendants.
The trees use heap indexing: for a node at index i, its left child is at 2*i + 1 and its right child is at 2*i + 2 (when those indices are within bounds).
Return the transformed array. The original contents of tree2 are irrelevant and will be overwritten; only the structure matters, which is guaranteed to match tree1.
Constraints
0 ≤ len(tree1) ≤ 10^4len(tree1) == len(tree2)-1000 ≤ tree1[i] ≤ 1000- Both arrays represent valid complete binary trees in level-order
- Nodes may have negative, zero, or positive values
Examples
Example 1
Input: compute_subtree_sums([1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 0])
Output: [28, 11, 16, 4, 5, 6, 7]
Example 2
Input: compute_subtree_sums([5, 3, 8, 1, 4], [9, 9, 9, 9, 9])
Output: [21, 8, 8, 1, 4]
Example 3
Input: compute_subtree_sums([10], [0])
Output: [10]
Example 4
Input: compute_subtree_sums([1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12])
Output: [21, 11, 9, 4, 5, 6]
Hints
Hint 1
Since a subtree sum depends on its children's subtree sums, you need a bottom-up evaluation order—think post-order traversal.
Hint 2
In heap indexing, every child has a larger index than its parent. What happens if you iterate from the last index down to zero?
Hint 3
Leaves (roughly the second half of the array) have no children, so their subtree sum is just their own value.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The subtree sum at any node equals the node's own value plus the subtree sums of its left and right children. This dependency structure requires post-order evaluation: we must compute children before their parent.
In a level-order array with heap indexing, every child index is strictly greater than its parent index (since 2*i + 1 > i for all non-negative i). This property gives us a simple iterative solution: iterate from the last index down to zero. By the time we reach index i, both of its children (if they exist) have already been processed.
Algorithm
- Create a result array of the same size as
tree1 - Iterate
ifromn-1down to0:- Start with
tree1[i]as the base value - If the left child exists at
2*i + 1, addresult[2*i + 1] - If the right child exists at
2*i + 2, addresult[2*i + 2] - Store the sum in
result[i]
- Start with
- Return the result array
Why It Works
Leaf nodes (roughly the second half of the array) have no children, so their subtree sum equals their own value. Internal nodes are processed after all their descendants, so when we compute result[i], both child subtrees have already been summed. Since every node in a subtree is counted exactly once—either as the root of its own subtree or as part of a child's subtree—this produces the correct total.
Complexity
- Time: O(n). Each of the n nodes is visited exactly once, performing constant-time arithmetic.
- Space: O(n) for the output array. No auxiliary data structures or recursion stack are needed—the iteration uses O(1) extra space.
from typing import List
def compute_subtree_sums(tree1: List[int], tree2: List[int]) -> List[int]:
n = len(tree1)
result = [0] * n
# Process nodes from bottom to top (reverse index order = post-order)
for i in range(n - 1, -1, -1):
subtree_sum = tree1[i]
left_child = 2 * i + 1
right_child = 2 * i + 2
if left_child < n:
subtree_sum += result[left_child]
if right_child < n:
subtree_sum += result[right_child]
result[i] = subtree_sum
return result