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.
- The number of nodes in both trees is in the range [0, 2000].
- -10⁴ <= Node.val <= 10⁴
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.valintoroot1, 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.
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.
Approach
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.
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.
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.
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.
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.
Code in Python, C++ and Java
root2, which is also empty, so nothing is attached here. No separate both-empty check is needed.root2, which is also empty, so nothing is attached here. No separate both-empty check is needed.Common pitfalls
Returning nothing when one node is missing
if not root1 or not root2:
return Noneif not root1:
return root2
if not root2:
return root1This 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
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)if not root1:
return root2
if not root2:
return root1Treating 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.
Edge cases
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.
Complexity
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.