Merge Two Binary Trees

You are given two binary trees `root1` and `root2`. Imagine laying one on top of the other: some positions are covered by both trees, some by only one. Merge them into a new tree. Where both trees have a node, the merged node holds the sum of the two values. Where only one tree has a node, that node is used as is. Return the merged tree. The merge starts from the roots of both trees.

30:00

Merge Two Binary Trees
easy
Free written solution
Topics
Companies

You are given two binary trees root1 and root2. Imagine laying one on top of the other: some positions are covered by both trees, some by only one.

Merge them into a new tree. Where both trees have a node, the merged node holds the sum of the two values. Where only one tree has a node, that node is used as is.

Return the merged tree. The merge starts from the roots of both trees.

Example 1:
Input: {"root1":[1,3,2,5],"root2":[2,1,3,null,4,null,7]}
Output: [3,4,5,5,4,null,7]
Constraints:
  • The number of nodes in both trees is in the range [0,2000][0, 2000].

  • −104≤Node.val≤104-10^4 \leq \text{Node.val} \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root1":[1,3,2,5],"root2":[2,1,3,null,4,null,7]}

Lay the two trees on top of each other and merge from the roots down.

root1

1352

root2

21437

merged (written into root1)

current call
both trees: sum
only root1: reused
only root2: reused
not filled yet / null
Variables
VariableValue
root11
root22
DepthFunction Call
Stack empty
0/13