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
Tree Merging ProcessTree 1132Tree 2213Merging ProcessOverlay & MergeMerged Result31+243+152+3🔑 Key InsightWe can modify the first tree in-place instead of creating a new tree!✓ When both nodes exist: tree1.val += tree2.val✓ When only tree2 has node: tree1 = tree2✓ When only tree1 has node: keep tree1 unchanged✓ Recursively apply to left and right subtreesTime: O(min(m,n)) | Space: O(height) for recursion stack
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!
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
89.3K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen