#617

Merge Two Binary Trees

newbie · 180 · lc easy +15 · verified · 79% accepted · 9,066 likes · top 90%

play →

Description

You are given two binary trees root1 and root2. Overlay them starting from their roots: wherever both trees have a node, the merged node's value is the sum of the two values; where only one tree has a node, that node carries into the result unchanged. Return the resulting merged tree.

Example 1:

Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
Output: [3,4,5,5,4,null,7]

Example 2:

Input: root1 = [1], root2 = [1,2]
Output: [2,2]

Code

1
2
3
4
5
6
7
8
9