Quick Overview

This question evaluates proficiency with binary tree algorithms and in-place subtree aggregation, emphasizing traversal strategies, shape verification, and handling subtree sums under linear-time and O(h) space constraints.

Transform tree using counterpart subtree sums

Company: Snowflake

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

Given the roots of two complete binary trees with identical structure, modify the node values of the second tree so that each node equals the sum of all node values in the subtree rooted at the same position in the first tree (including that corresponding root). Provide an algorithm that runs in linear time relative to the number of nodes and uses at most O(h) extra space, where h is tree height. Describe recursion vs. iteration choices, how you verify shape identity, and how you would test edge cases (single node, skewed last level, large values).

Overview: This question evaluates proficiency with binary tree algorithms and in-place subtree aggregation, emphasizing traversal strategies, shape verification, and handling subtree sums under linear-time and O(h) space constraints.

Given identical complete-tree arrays, replace each second-tree node with the subtree sum at the same position in the first tree.

Constraints

  • Trees have identical array shape

Examples

Input: ([1, 2, 3], [0, 0, 0])

Expected Output: [6, 2, 3]

Explanation: Root sum and leaf sums.

Input: ([5], [9])

Expected Output: [5]

Explanation: Single node.

Hints

  1. Postorder traversal computes each subtree sum once.

Transform Tree by Counterpart Subtree Sums

mediumSnowflakeSoftware Engineer

Given identical complete-tree arrays, replace each second-tree node with the subtree sum at the same position in the first tree.

Examples

Example 1
Input
([1, 2, 3], [0, 0, 0])
Output
[6, 2, 3]
Notes
Root sum and leaf sums.
Example 2
Input
([5], [9])
Output
[5]
Notes
Single node.

Constraints

  • •Trees have identical array shape

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def solution(tree1: list[int], tree2: list[int]) -> list[int]:
Sample call
solution([1, 2, 3], [0, 0, 0])
Language
Case 1
Input
([1, 2, 3], [0, 0, 0])
Expected
[6, 2, 3]
Case 2
Input
([5], [9])
Expected
[5]

Browse More Questions