Skip to content
Problem 617 · LeetCode 617(opens in a new tab)

Merge Two Binary Trees

EasyRecursion

You are given the roots of two binary trees, root1 and root2. Lay one tree on top of the other, lining up the roots, and combine them into one tree.

Where both trees have a node in the same spot, the combined node holds the sum of the two values. Where only one tree has a node, that node is used as it is. Return the root of the combined tree.

Example 1

Input:  root1 = [4, 2, 7, 1], root2 = [3, 5, 6, null, 8, null, 9]
Output: [7, 7, 13, 1, 8, null, 9]
Why:    4+3, 2+5 and 7+6 overlap; 1, 8 and 9 come from one side
2 more examples and the constraints

Example 2

Input:  root1 = [], root2 = [5, 3]
Output: [5, 3]
Why:    the first tree is empty, so the answer is the second

Example 3

Input:  root1 = [1, null, 2], root2 = [3, 4]
Output: [4, 4, 2]
Why:    the roots add to 4; each child exists on one side only

Constraints

  • Each tree has between 0 and 2,000 nodes
  • −10,000 ≤ each node value ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Build a new treeO(m + n)
  2. Merge into root1, reuse the restO(min(m, n))

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for trees of 2,000 nodesVerdict
Build a new treeO(m + n)
Passes; keeps the inputs intact
Merge into root1O(min(m, n))
Best; skips one-sided subtrees

m, n = nodes in the two trees, h = height of the overlap.

Edge cases to test

  • Both trees empty. Return null, which prints as [].
  • One tree empty. The answer is the other tree, unchanged.
  • Values cancel. A node of 5 over a node of −5 becomes 0; it still exists in the answer.
  • Different shapes. [1, null, 2] with [3, 4]: the left child comes from root2 and the right from root1.
  • Long chains. Two chains of 1,000 nodes make the recursion 1,000 calls deep.

Common mistakes

  • Reading root1.val or root2.left before checking that the node exists.
  • Returning null when only one side is empty, which drops that whole subtree.
  • Dropping a node whose sum is 0, as if a zero value meant a missing node.

How to talk through it

  1. 1Clarify. May I change the input trees, or must I build a new one? Can either tree be empty?
  2. 2Name the cases. Both nodes present: add. One missing: return the other. Both missing: null.
  3. 3Code the recursion. Handle the empty sides first, then add and recurse left and right.
  4. 4State the cost. Only the overlap is visited: O(min(m, n)) time, O(h) stack.
  5. 5Test out loud. Run one empty tree, two trees of different shapes, and values that cancel to 0.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?