Merge Two Binary Trees (LeetCode 617): Solution and Explanation
Given two binary trees, overlay them: where both have a node the merged node holds the sum, and where only one has a node that node is used as is. Return the merged tree.
Intuition
Picture the two trees drawn on the same grid. Every position is covered by both trees, by just one, or by neither. The merged tree has a node exactly where at least one input does.
Where both trees have a node, the answer is clear: one node with the sum, and its children come from merging the two left children and the two right children. That is the same problem one level down, so recursion fits.
Where only one tree has a node, there is nothing to combine anywhere below it either, because the other tree is empty there. We can return that node and its whole subtree in one step, without visiting any of it. That is why the work only depends on the overlap.
Approach: Recursive overlay into root1
- If
root1is null, returnroot2(which may also be null). - If
root2is null, returnroot1. - Both exist: add
root2.valintoroot1.val. - Set
root1.left = mergeTrees(root1.left, root2.left). - Set
root1.right = mergeTrees(root1.right, root2.right). - Return
root1.
Step-by-step example
root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
- Roots 1 and 2 overlap: the root becomes 3.
- Left children 3 and 1 overlap: that node becomes 4.
- Under it, the left position has 5 in root1 and nothing in root2, so 5 is reused. The right position has only root2's 4, so 4 is reused.
- Right children 2 and 3 overlap: that node becomes 5.
- Its left position is empty in both trees. Its right position has only root2's 7, which is reused.
- Result: [3,4,5,5,4,null,7].
Code: Python, Java, C++
1class Solution:
2 def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
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 root11class Solution {
2 public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
3 if (root1 == null) return root2;
4 if (root2 == null) return root1;
5 root1.val += root2.val;
6 root1.left = mergeTrees(root1.left, root2.left);
7 root1.right = mergeTrees(root1.right, root2.right);
8 return root1;
9 }
10}1class Solution {
2public:
3 TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
4 if (!root1) return root2;
5 if (!root2) return root1;
6 root1->val += root2->val;
7 root1->left = mergeTrees(root1->left, root2->left);
8 root1->right = mergeTrees(root1->right, root2->right);
9 return root1;
10 }
11};Time and space complexity
O(min(n, m))
Recursion only continues at positions where both trees have a node, and there are at most min(n, m) of those. Positions covered by one tree are returned in O(1) as whole subtrees.
O(h)
The recursion stack is as deep as the overlapping part of the trees, at most the smaller height.
Other approaches
Build a fresh tree (time O(min(n, m)), space O(h))
Create new nodes instead of writing into root1, so neither input is changed. Subtrees that exist in only one tree are still shared unless you copy them, which would cost O(n + m).
Iterative with a stack of pairs (time O(min(n, m)), space O(h))
Push (node1, node2) pairs. For each pair add the values, and for each side either attach node2's child when node1's is missing or push the pair of children. Avoids deep recursion on skewed trees.
Common mistakes
- Recursing into a position where one tree is null and building copies node by node. It works but is slower and more code than returning the existing subtree.
- Forgetting to assign the recursive result to
root1.left/root1.right. Subtrees that exist only in root2 are then lost. - Reading
root2.leftafter checking onlyroot1. Both null checks must come before any field access.
Frequently asked questions
Is it fine to modify root1?
Yes. The problem only asks for the merged tree, and reusing root1's nodes saves allocations. Build new nodes if the caller needs the inputs unchanged.
Why can a whole subtree be returned without visiting it?
If root2 is null at some position, it is null at every position below it, so every node there simply keeps its value from root1. The same holds the other way round.
What if both trees are empty?
The first check sees root1 is null and returns root2, which is also null, so the result is an empty tree.