← Questions

Merge neighbor sums from many binary trees into the last

0
SnowflakeCoding

You are given a list trees of binary trees (each given by its root, possibly empty). The neighbor sum of a node is its own value plus the values of its left and right children, where a missing child counts as 0.

Treat every tree except the last one as a source. The last tree is the target. Process the sources from left to right. For each node in a source, find the node at the same position in the target. A position is the path from the root: the root, then left or right at each step.

  • If the target has a node there, add the source node's neighbor sum to its value.
  • If the target has no node there, create one whose value is the neighbor sum, and attach it at that position.

Always compute neighbor sums from the source trees' original values. Do not modify the source trees. Return the root of the updated target. Return None if trees is empty, or if every tree is empty.

def copy_neighbor_sums(trees: list[Optional[TreeNode]]) -> Optional[TreeNode]: ...

Constraints

  • 0 <= len(trees) <= 10^3
  • Up to 10^5 nodes in total; node values are integers (they may be negative)
  • Trees can be very unbalanced (depth up to 10^5)

Example 1 (trees written in level order, None = missing)

trees = [[2, 4, 1], [10, 1]]

The source root's neighbor sum is 2 + 4 + 1 = 7, so the target root becomes 17. The left node's neighbor sum is 4, so the target's left node becomes 5. The target has no right child, so a node with value 1 is created.
Result: [17, 5, 1].

Example 2

trees = [[1, 2], [3], [0]]

Each source adds 3 to the root (1 + 2 + 0, then 3 + 0 + 0), so the root becomes 6. The first source's left child creates a node with value 2.
Result: [6, 2].

Reconstructed from the reported question; details may differ from what interviewers ask.

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