← Questions

Fill a second tree with subtree sums of the first

0
SnowflakeCodingLast asked Sep 2025

A coding interview question asked in Snowflake's two coding screens round, last asked Sep 2025. It tests binary trees, dfs and recursion.

You get the roots of two complete binary trees with exactly the same shape. Change the values of the second tree so that each node holds the sum of all values in the subtree of the first tree at the same position, including that node itself. The first tree is not modified.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • fill_subtree_sums(a: TreeNode | None, b: TreeNode | None) -> None writes the sums into b in place.

For testing, a complete tree can be written as its level-order array (node i has children 2i + 1 and 2i + 2).

Example

a = [1, 2, 3, 4, 5, 6]          b = [0, 0, 0, 0, 0, 0]
after: b = [21, 11, 9, 4, 5, 6]  # 11 = 2 + 4 + 5, 9 = 3 + 6, 21 = everything

a = [5]   b = [9]   ->   b = [5]

Constraints

  • Up to 10^6 nodes; sums may exceed 32 bits.
  • Linear time and at most O(h) extra space, where h is the height.

Clarifying questions

  • Are the shapes guaranteed identical, or should a mismatch raise an error?
  • May values be negative, and how large can sums get?
  • Is recursion acceptable at this height, or must it be iterative?
  • Should the first tree be left untouched?

What a strong answer covers

  • A post-order walk of both trees in lockstep that returns the subtree sum of a's node and writes it into b's node; each node is visited once, O(n) time.
  • O(h) space from the recursion stack, and h = O(log n) because the trees are complete; an iterative version with an explicit stack.
  • Shape verification as part of the same walk (one side null and the other not).
  • 64-bit sums, and tests for a single node, a last level that is only partly filled, and large values.

Follow-ups

  • The trees are given as arrays: do it with no recursion at all.
  • Write the sums into a itself, in place, with no second tree.
  • The trees are arbitrary (not complete) and may differ in shape: how do you report where they diverge?

Where it's asked

  • Snowflake · Two coding screens · Last asked Sep 202560 min · Two back-to-back live coding rounds, often on the same day; some loops pair coding with system design · Varies: some screens forbid AI, some 2026 screens allow it. The scheduling email says.

What it tests

binary trees · dfs · recursion

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding