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
Merge Two Binary Trees INPUT Tree 1: [1,3,2,5] 1 3 2 5 Tree 2: [2,1,3,null,4,null,7] 2 1 3 4 7 ALGORITHM (DFS) 1 Base Cases If node1 null, return node2 If node2 null, return node1 2 Merge Roots Sum values: 1+2=3 Create merged node 3 Recurse Left DFS on left subtrees 3+1=4, then 5+null=5, 4 4 Recurse Right DFS on right subtrees 2+3=5, then 7 Merge Example: 1 + 2 = 3 FINAL RESULT Merged Tree 3 4 5 5 4 7 Output: [3,4,5,5,4,null,7] OK - Trees Merged! Time: O(n), Space: O(h) Key Insight: DFS naturally handles the recursive tree structure. At each node position, we check three cases: 1) Both nodes exist --> sum values 2) Only one exists --> use that node 3) Neither exists --> null The recursion builds the merged tree from bottom-up as the call stack unwinds. TutorialsPoint - Merge Two Binary Trees | DFS Approach
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