Skip to main content

Merge Two Binary Trees - Solution & Explanation

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree14 min readAsked at: Amazon, Microsoft, Meta +5
Practice this problem

Problem Statement

You are given two binary trees root1 and root2.

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return the merged tree.

Note: The merging process must start from the root nodes of both trees.

 

Example 1:

Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
Output: [3,4,5,5,4,null,7]

Example 2:

Input: root1 = [1], root2 = [1,2]
Output: [2,2]

 

Constraints:

  • The number of nodes in both trees is in the range [0, 2000].
  • -104 <= Node.val <= 104

Approach Overview

Problem Overview: You receive two binary trees. If two nodes overlap, their values are summed. If only one node exists at a position, that node becomes part of the merged tree. The goal is to return the root of the merged tree.

Approach 1: Recursive Depth-First Search (O(n) time, O(h) space)

This approach uses recursion to traverse both trees simultaneously. For each pair of nodes, add their values and recursively merge their left and right children. If one node is null, return the other node directly. The recursion naturally follows the structure of the trees, making the implementation concise and easy to reason about. Time complexity is O(n) where n is the total number of nodes across both trees, because each node is processed once. Space complexity is O(h) from the recursion stack, where h is the height of the tree.

This approach directly leverages Depth-First Search traversal on a Binary Tree. It modifies or builds nodes as the recursion unwinds.

Approach 2: Iterative Traversal with Queue or Stack (O(n) time, O(n) space)

An iterative strategy avoids recursion by explicitly managing traversal with a queue (BFS) or stack (DFS). Start with the pair of root nodes. While the data structure is not empty, pop a node pair and merge their values. For children, if both nodes exist, push the pair for later processing. If a child exists in only one tree, attach it directly to the merged tree. This simulates the recursive traversal but uses an explicit structure to track work.

The algorithm still processes each node once, giving O(n) time complexity. Space complexity becomes O(n) in the worst case due to the queue or stack holding node pairs. Using a queue corresponds to Breadth-First Search, which processes the tree level by level.

Recommended for interviews: The recursive DFS solution is the expected answer. It clearly shows understanding of binary tree traversal and keeps the code minimal. Interviewers often look for the base-case handling (null nodes) and correct recursive merging of children. The iterative version demonstrates deeper control over traversal mechanics and is useful when recursion depth might be a concern.

Approach 1: Recursive Approach

This approach utilizes recursion to traverse both trees simultaneously. If both node values are non-null, we sum them up as the new value and recursively merge their left and right children. If one node is null, we return the non-null node.

This C solution uses a recursive function mergeTrees. We check if either of the current nodes is null and return the other node. If neither is null, we sum their values, then recursively merge their left and right children.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n); Space Complexity: O(h), where n is the total number of nodes and h is the height of the tree.

Try this approach in the editor →

Approach 2: Iterative Approach

This approach uses an iterative method with a stack to simulate the recursive calls for merging the two binary trees. We traverse the trees using a stack and merge nodes at each level iteratively.

This C solution uses a stack to perform an iterative merge of the binary trees. We manage pairs of nodes to process, summing their values and pushing their children onto the stack for subsequent processing.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n); Space Complexity: O(h), where n is the total number of nodes and h is the maximum height of the two trees.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Rust

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Recursive Approach

Time Complexity: O(n); Space Complexity: O(h), where n is the total number of nodes and h is the height of the tree.

Iterative Approach

Time Complexity: O(n); Space Complexity: O(h), where n is the total number of nodes and h is the maximum height of the two trees.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive Depth-First SearchO(n)O(h)Best general solution. Clean code and natural fit for binary tree recursion.
Iterative Traversal (Queue/Stack)O(n)O(n)Useful when avoiding recursion or when recursion depth may cause stack overflow.

Video Solution

Merge Two Binary Trees - Leetcode 617NeetCode70,833 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Merge Two Binary Trees easy or hard?
Merge Two Binary Trees is classified as an Easy problem on LeetCode. It mainly tests understanding of binary tree traversal and handling null nodes during recursion or iteration.
Merge Two Binary Trees Python/Java solution
Python and Java implementations usually follow the recursive DFS pattern. The function checks for null nodes, sums the values of overlapping nodes, and recursively merges the left and right children before returning the merged root.
How to solve Merge Two Binary Trees in O(n)?
Traverse both trees simultaneously using DFS or BFS. When two nodes overlap, sum their values and continue merging their children. If one node is null, return the other node directly. Since every node is processed once, the algorithm runs in O(n) time.
What is the best approach for Merge Two Binary Trees?
The recursive depth-first search approach is the most common solution. Traverse both trees simultaneously, sum overlapping nodes, and recursively merge their children. This method processes each node once and runs in O(n) time with O(h) recursion stack space.
Is Merge Two Binary Trees asked at Google/Amazon/Meta?
Binary tree traversal and merging problems appear frequently in interviews at companies like Amazon and Meta. While this exact problem may vary in wording, the core concept—simultaneous traversal of two trees—is commonly tested.
What data structure is used in Merge Two Binary Trees?
The problem uses the binary tree data structure. The solution typically applies depth-first search with recursion or breadth-first search using a queue to traverse and merge nodes.
What is the time complexity of Merge Two Binary Trees?
The time complexity is O(n), where n is the total number of nodes across both trees. Each node is visited once during the traversal. Space complexity is O(h) for recursion depth in the DFS approach or O(n) when using an iterative queue or stack.

Ready to solve this problem?

Practice Merge Two Binary Trees with our built-in code editor and test cases.

Practice on FleetCode