KatInterview

Subtree Sum Replacement in Level-Order Arrays

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsbinary-treespost-order-traversalcomplete-binary-tree

Last 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^4
  • len(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.