LeetCode #617 Easy

Merge Two Binary Trees

Merge Two Binary Trees is LeetCode 617 (Easy). Lay root2 over root1, starting at the two roots. 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 it is. Return the root of the merged tree.

Each tree has up to 2,000 nodes, so a chain-shaped tree can be 2,000 levels deep.

Constraints
  • The number of nodes in both trees is in the range [0, 2000].
  • -10⁴ <= Node.val <= 10⁴
treedfsrecursion
Open on LeetCode ↗
02

Intuition

Walk both trees in step, always at the same position in each, starting at the two roots. At every position there are three cases, and two of them end the walk right away:

  • Only one node exists: its whole subtree has nothing to merge with, so return that node, children and all, unchanged. The same check covers both nodes missing, because returning the missing one returns nothing.
  • Both exist: add root2.val into root1, then merge the two left children and the two right children.

Because the walk stops wherever either tree runs out, it only visits positions where both trees have a node.

How to spot this pattern

Two trees compared or combined position by position, root with root, left with left, right with right, is a paired DFS. Same Tree and Symmetric Tree use the same shape.

03

Approach

Try it first

Before reading on, list what the merge should return when one of the two nodes is missing, and when both are missing. Then decide whether you need to visit the nodes of a subtree that has no partner. Aim to touch only the overlap of the two trees.

1

Return the other tree when one node is missing

If root1 is empty, return root2; if root2 is empty, return root1. The surviving subtree is already the right answer for this position, so it is attached whole, without visiting its nodes.

2

Add the values when both nodes exist

Add root2.val into root1.val, so tree 1's node becomes the merged node. Reusing it saves creating a new one, and the problem allows the input trees to change.

3

Merge the children pairwise

Set root1.left to the merge of the two left children and root1.right to the merge of the two right children. Left pairs with left and right with right, because the merge is position by position.

4

Return root1

It now holds the merged subtree for this position. The caller stores it as its own left or right child, which links the merged tree together from the bottom up.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def mergeTrees(self, root1, root2):
▶3 if not root1:
▶4 return root2
▶5 if not root2:
▶6 return root1
▶7 root1.val += root2.val
▶8 root1.left = self.mergeTrees(root1.left, root2.left)
▶9 root1.right = self.mergeTrees(root1.right, root2.right)
▶10 return root1
tree 1tree 2132521347mergednothing yetstart at both roots
tree 14 nodes
tree 25 nodes
The merge walks both trees together, always at the same position in each. Dashed red circles will mark a position where one tree has no node.
tree 1tree 2132521347merged3both have a node → sum 3, then merge the children
root11
root22
placed1 node
Both trees have a node at the roots, so add the values: 1 + 2 = 3, stored in tree 1's node. Next, the two left children are merged, then the two right children.
tree 1tree 2132521347merged34both have a node → sum 4, then merge the children
root13
root21
placed1 node
Both trees have a node at root → left, so add the values: 3 + 1 = 4, stored in tree 1's node. Next, the two left children are merged, then the two right children.
tree 1tree 2132521347merged345tree 2 has no node → keep tree 1's 5
root15
root2None
placed1 node
At root → left → left only tree 1 has a node, so return root1. Node 5 stays as it is.
tree 1tree 2132521347merged3454tree 1 has no node → take tree 2's 4 as is
root1None
root24
placed1 node
At root → left → right only tree 2 has a node. There is nothing to add it to, so return root2: node 4 is attached unchanged.
tree 1tree 2132521347merged34554both have a node → sum 5, then merge the children
root12
root23
placed1 node
Both trees have a node at root → right, so add the values: 2 + 3 = 5, stored in tree 1's node. Next, the two left children are merged, then the two right children.
tree 1tree 2132521347merged34554both missing → return nothing
root1None
root2None
placed0 nodes
Neither tree has a node at root → right → left. The first check returns root2, which is also empty, so nothing is attached here. No separate both-empty check is needed.
tree 1tree 2132521347merged345547tree 1 has no node → take tree 2's 7 as is
root1None
root27
placed1 node
At root → right → right only tree 2 has a node. There is nothing to add it to, so return root2: node 7 is attached unchanged.
tree 1tree 2132521347merged345547return the merged root (6 nodes)
nodes6
sums3positions in both trees
Every call has returned, and each parent stored its children's results, so tree 1 now is the merged tree. Only 3 positions needed a sum; the other nodes were reused whole.
05

Common pitfalls

Returning nothing when one node is missing

✗ Wrong
if not root1 or not root2:
    return None
✓ Right
if not root1:
    return root2
if not root2:
    return root1

This throws away the subtree that does exist. For root1 = [1] and root2 = [1, 2], node 2 disappears and the result is [2] instead of [2, 2].

Reading a child of a missing node

✗ Wrong
if not root1 and not root2:
    return None
val = (root1.val if root1 else 0) + (root2.val if root2 else 0)
node = TreeNode(val)
node.left = self.mergeTrees(root1.left, root2.left)
✓ Right
if not root1:
    return root2
if not root2:
    return root1

Treating a missing node as 0 handles the value but not the children. For [1] and [1, 2], the call on (missing, 2) builds node 2 and then reads root1.left of a missing node, which crashes.

06

Edge cases

Two long chains

If both trees are chains of 2,000 nodes down the same side, the recursion is 2,000 calls deep. C++ and Java handle that, but Python stops at 1,000 nested calls by default: raise the limit with sys.setrecursionlimit(10000) or use a stack of node pairs.

07

Complexity

Time
O(min(m, n))
Space
O(min(m, n))
m and n are the node counts. Only positions where both trees have a node are visited, so the work is the size of the overlap. The recursion stack holds one call per level of the overlap: about log of its size when balanced, up to its size for a chain.
08

Merge Two Binary Trees FAQ

Can it be done without recursion?

Push the pair (root1, root2) on a stack, after handling an empty root. Pop a pair and add the values. For each side, push the two children as a pair when both exist; when only root2 has a child, attach it to root1. When neither condition holds, root1's child, or nothing, stays. Return root1 when the stack is empty.

How do I keep the input trees unchanged?

Create a new node holding the sum instead of writing into root1. The one-missing case still returns an existing subtree, so the result shares those nodes with the inputs; copy that subtree too if the result must be fully separate.