Ctrl K

Overlay Two Trees

Easy
You are given the roots of two binary trees, base and top. Lay top over base so that the roots line up, then match nodes position by position: left child with left child, right child with right child. Build a new tree by this rule: - where both trees have a node at the same position, the result has a node whose value is their sum; - where only one tree has a node, that node goes into the result together with its whole subtree. Return the root of the resulting tree (an empty tree if both inputs are empty).
Example 1
base=tree_node([4, 1, 6, None, 2]), top=tree_node([3, -1, None, 5]) → [7, 0, 6, 5, 2]

The roots overlap: 4 + 3 = 7. Left children: 1 + (-1) = 0. That node's left child exists only in top (5) and its right child only in base (2). The root's right child exists only in base (6).

Example 2
base=tree_node([]), top=tree_node([8, None, 9]) → [8, None, 9]

The first tree is empty, so the result is just the second one.

Example 3
base=tree_node([2, 2, 2]), top=tree_node([5]) → [7, 2, 2]
Constraints
  • 0 ≤ number of nodes in each tree ≤ 2000
  • -10⁴ ≤ Node.val ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIdentical Trees EasyMirror-Image Tree EasyTree Height EasyNearest Leaf Depth EasyLeaf Path With a Given Total Easy
loading Python…
Input
base=tree_node([4, 1, 6, None, 2]), top=tree_node([3, -1, None, 5])
Expected
[7, 0, 6, 5, 2]

Run checks the first 3 tests in your browser. Submit checks all 61 tests on the server, hidden ones included.