Merge Two Binary Trees - Problem
You have two binary trees that need to be combined into one! Imagine placing one tree over another - when nodes from both trees exist at the same position, their values should be added together. When only one tree has a node at a position, that node becomes part of the merged tree unchanged.
Given two binary tree roots root1 and root2, return the root of the new merged binary tree.
Merge Rules:
- If both trees have nodes at the same position → sum their values
- If only one tree has a node → use that node as-is
- If neither tree has a node → no node in result
The merging process starts from the root nodes and works through the entire tree structure.
Input & Output
example_1.py — Basic Tree Merge
$
Input:
root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
›
Output:
[3,4,5,5,4,null,7]
💡 Note:
The merged tree combines overlapping nodes: root (1+2=3), left child (3+1=4), right child (2+3=5). Non-overlapping nodes like 5, 4, and 7 are copied directly.
example_2.py — One Empty Tree
$
Input:
root1 = [1], root2 = [1,2]
›
Output:
[2,2]
💡 Note:
Root nodes merge (1+1=2), and since root1 has no left child, root2's left child (2) is copied to the result.
example_3.py — Empty Tree Edge Case
$
Input:
root1 = [], root2 = [1,2,3]
›
Output:
[1,2,3]
💡 Note:
When one tree is empty, the result is simply the other tree. No merging is needed.
Constraints
- The number of nodes in both trees is in the range [0, 2000]
- -104 ≤ Node.val ≤ 104
- Trees can be of different heights and structures
Visualization
Tap to expand
Understanding the Visualization
1
Overlay at Root
Place trees on top of each other, starting from roots
2
Merge Overlapping
Where both trees have nodes, add their values together
3
Keep Singles
Where only one tree has a node, keep that node unchanged
4
Recurse Subtrees
Apply same process to left and right subtrees
Key Takeaway
🎯 Key Insight: Instead of creating an entirely new tree, we can modify one of the input trees in-place, which is more memory-efficient and elegant. The recursive structure naturally handles all edge cases!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code