Quick Overview

Given two binary trees in level-order form, overlay them with their roots aligned so overlapping nodes add their values and all other nodes carry over, then return the merged tree in the same format. It tests simultaneous tree traversal, level-order serialization and handling of empty or very deep trees.

Overlay Two Binary Trees by Summing Values at Overlapping Positions

Company: Snowflake

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Technical Screen

Given two binary trees, overlay one on the other with their roots aligned and return the merged tree. Wherever both trees have a node at the same position, the merged tree has one node whose value is the sum of the two values. Wherever only one tree has a node, the merged tree has a node with that value. ### Function Signature ```python def merge_trees(tree1: list[int | None], tree2: list[int | None]) -> list[int | None]: ``` ### Rules - A node's position is the sequence of left and right steps from the root to it. The merged tree has a node at a position exactly when at least one input tree has a node there, so its shape is the union of the two shapes. - Trees are given and returned in level order: the root's value first, then, for each present node in level order, its left child and then its right child, with `None` for a missing child. Children of a missing node are not listed, trailing `None` entries are removed, and the empty tree is `[]`. - A merged node whose values sum to 0 is still a node and appears as `0`. - Return the level-order list of the merged tree in exactly this format, which makes the output unique. ### Constraints - Each tree has between 0 and 2000 nodes, and a tree can be a single chain, so its depth can reach 2000. - `-10^4 <= value <= 10^4` for every node, so every merged value lies in `[-2 * 10^4, 2 * 10^4]`. - Both inputs are valid level-order lists in the format above. ### Examples **Example 1** ```text Input: tree1 = [4, 2, 7, None, 3], tree2 = [1, 5, None, 6] Output: [5, 7, 7, 6, 3] ``` The roots overlap (4 + 1 = 5) and so do the left children (2 + 5 = 7); the right child 7 exists only in `tree1`. Under the merged left child, the left child 6 comes only from `tree2` and the right child 3 only from `tree1`. **Example 2** ```text Input: tree1 = [], tree2 = [1, None, 2] Output: [1, None, 2] ``` **Example 3** ```text Input: tree1 = [-3, None, 8], tree2 = [2, 4, -8] Output: [-1, 4, 0] ``` The right children sum to 0, and that node stays in the tree.

Overview: Given two binary trees in level-order form, overlay them with their roots aligned so overlapping nodes add their values and all other nodes carry over, then return the merged tree in the same format. It tests simultaneous tree traversal, level-order serialization and handling of empty or very deep trees.

Read the full Snowflake Software Engineer interview experience this question came from

Given two binary trees, overlay one on the other with their roots aligned and return the merged tree. - A node's position is the sequence of left and right steps from the root to it. The merged tree has a node at a position exactly when at least one input tree has a node there, so its shape is the union of the two shapes. - Wherever both trees have a node at the same position, the merged tree has one node whose value is the sum of the two values. Wherever only one tree has a node, the merged tree has a node with that value. - A merged node whose values sum to 0 is still a node and appears as `0`. **Tree format.** Trees are given and returned in level order: the root's value first, then, for each present node in level order, its left child and then its right child, with a null marker for a missing child. Children of a missing node are not listed, trailing null markers are removed, and the empty tree is `[]`. The null marker is `None` in Python, `null` in JavaScript, `null` in Java (the lists hold `Integer` values) and `std::nullopt` in C++ (the vectors hold `std::optional<int>`). Implement `merge_trees(tree1, tree2)` and return the level-order list of the merged tree in exactly this format, which makes the output unique. **Example 1** ```text Input: tree1 = [4, 2, 7, None, 3], tree2 = [1, 5, None, 6] Output: [5, 7, 7, 6, 3] ``` The roots overlap (4 + 1 = 5) and so do the left children (2 + 5 = 7); the right child 7 exists only in `tree1`. Under the merged left child, the left child 6 comes only from `tree2` and the right child 3 only from `tree1`. **Example 2** ```text Input: tree1 = [-3, None, 8], tree2 = [2, 4, -8] Output: [-1, 4, 0] ``` The right children sum to 0, and that node stays in the tree. **Constraints** - Each tree has between 0 and 2000 nodes, and a tree can be a single chain, so its depth can reach 2000. - `-10^4 <= value <= 10^4` for every node, so every merged value lies in `[-2 * 10^4, 2 * 10^4]`. No value can exceed 2^31-1, so a 32-bit `int` is enough in every language. - Both inputs are valid level-order lists in the format above.

Constraints

  • Each tree has between 0 and 2000 nodes, and a tree can be a single chain, so its depth can reach 2000.
  • -10^4 <= value <= 10^4 for every node, so every merged value lies in [-2 * 10^4, 2 * 10^4]. No value can exceed 2^31-1.
  • Both inputs are valid level-order lists in the format above: children of a missing node are not listed, trailing null markers are removed, and the empty tree is [].

Examples

Input: ([4, 2, 7, None, 3], [1, 5, None, 6])

Expected Output: [5, 7, 7, 6, 3]

Explanation: Source example 1: roots and left children overlap; 7, 6 and 3 each come from one tree.

Input: ([-3, None, 8], [2, 4, -8])

Expected Output: [-1, 4, 0]

Explanation: Source example 3: the right children 8 and -8 sum to 0 and that node stays as 0.

Hints

  1. A node's position is its path of left and right steps from the root. Find a way to visit the two nodes at the same position together.
  2. The lists skip the children of missing nodes, so a node's index in the list does not tell you where its children are. Work out the real parent-child links before you combine anything.
  3. A tree can be a chain 2000 levels deep, and a merged value of 0 is still a node. Only trailing null markers are dropped from the output.

Overlay Two Binary Trees by Summing Overlapping Nodes

hardSnowflakeSoftware Engineer

Given two binary trees, overlay one on the other with their roots aligned and return the merged tree.

  • A node's position is the sequence of left and right steps from the root to it. The merged tree has a node at a position exactly when at least one input tree has a node there, so its shape is the union of the two shapes.
  • Wherever both trees have a node at the same position, the merged tree has one node whose value is the sum of the two values. Wherever only one tree has a node, the merged tree has a node with that value.
  • A merged node whose values sum to 0 is still a node and appears as 0.

Tree format. Trees are given and returned in level order: the root's value first, then, for each present node in level order, its left child and then its right child, with a null marker for a missing child. Children of a missing node are not listed, trailing null markers are removed, and the empty tree is []. The null marker is None in Python, null in JavaScript, null in Java (the lists hold Integer values) and std::nullopt in C++ (the vectors hold std::optional<int>).

Implement merge_trees(tree1, tree2) and return the level-order list of the merged tree in exactly this format, which makes the output unique.

Example 1

Input:  tree1 = [4, 2, 7, None, 3], tree2 = [1, 5, None, 6]
Output: [5, 7, 7, 6, 3]

The roots overlap (4 + 1 = 5) and so do the left children (2 + 5 = 7); the right child 7 exists only in tree1. Under the merged left child, the left child 6 comes only from tree2 and the right child 3 only from tree1.

Example 2

Input:  tree1 = [-3, None, 8], tree2 = [2, 4, -8]
Output: [-1, 4, 0]

The right children sum to 0, and that node stays in the tree.

Constraints

  • Each tree has between 0 and 2000 nodes, and a tree can be a single chain, so its depth can reach 2000.
  • -10^4 <= value <= 10^4 for every node, so every merged value lies in [-2 * 10^4, 2 * 10^4]. No value can exceed 2^31-1, so a 32-bit int is enough in every language.
  • Both inputs are valid level-order lists in the format above.

Examples

Example 1
Input
([4, 2, 7, None, 3], [1, 5, None, 6])
Output
[5, 7, 7, 6, 3]
Notes
Source example 1: roots and left children overlap; 7, 6 and 3 each come from one tree.
Example 2
Input
([-3, None, 8], [2, 4, -8])
Output
[-1, 4, 0]
Notes
Source example 3: the right children 8 and -8 sum to 0 and that node stays as 0.

Constraints

  • •Each tree has between 0 and 2000 nodes, and a tree can be a single chain, so its depth can reach 2000.
  • •-10^4 <= value <= 10^4 for every node, so every merged value lies in [-2 * 10^4, 2 * 10^4]. No value can exceed 2^31-1.
  • •Both inputs are valid level-order lists in the format above: children of a missing node are not listed, trailing null markers are removed, and the empty tree is [].

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 merge_trees(tree1: list[int | None], tree2: list[int | None]) -> list[int | None]:
Sample call
merge_trees([4, 2, 7, None, 3], [1, 5, None, 6])
Language
Case 1
Input
([4, 2, 7, None, 3], [1, 5, None, 6])
Expected
[5, 7, 7, 6, 3]
Case 2
Input
([-3, None, 8], [2, 4, -8])
Expected
[-1, 4, 0]

Browse More Questions

Show the approach

Approach

Rebuild, then walk both trees together.

  1. Rebuild each tree from its level-order list. The first entry is the root. Then each created node, taken in creation order, consumes the next entry as its left child and the entry after that as its right child, and None means no child. A queue of created nodes reproduces the format's definition exactly: children of missing nodes are never listed, and a list that ends early (trailing None removed) leaves the remaining children missing. Each tree is stored as arrays of values and left/right child indices (-1 for none).

  2. Walk both trees together breadth-first over pairs (a, b). Here a is a node of tree1 or -1, b is a node of tree2 or -1, and at least one is present. Each pair is one node of the merged tree, at one position, and its value is the sum of the values that are present. For each dequeued pair, form the left pair from the two left children and the right pair from the two right children. If both sides of a child pair are -1, the merged tree has no node there, so append None. Otherwise append the pair's value and enqueue the pair. Finally strip the trailing None entries.

Invariant: the queue holds merged nodes in level order, and the output so far is the root followed by the child slots of every node already dequeued. A merged node exists at a position exactly when one of the trees has a node there, which is the union rule. Missing merged nodes are never enqueued, so their children are never listed. That is exactly the source's serialization, which is unique, so the result is the required output.

Edge cases: two empty trees return []. If one tree is empty, the other comes back in canonical form. A merged sum of 0 is appended as 0, because only None counts as missing and only trailing None entries are trimmed. Input nodes whose value is 0 are real nodes. Chains of depth 2000 are handled without recursion, because both phases are iterative.

Time complexity:
O(n1 + n2)
Space complexity:
O(n1 + n2)