#617
Merge Two Binary Trees
EasyTreeDepth-First SearchBreadth-First SearchBinary TreeRecursionTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal solution uses recursion to traverse both trees simultaneously, merging nodes as we go. This approach is efficient because it only visits each node once, leading to a linear time complexity.
⚙️
Algorithm
5 steps- 1Step 1: If both nodes are null, return null.
- 2Step 2: If one node is null, return the other node.
- 3Step 3: Create a new node with the sum of both nodes' values.
- 4Step 4: Recursively merge the left children of both nodes.
- 5Step 5: Recursively merge the right children of both nodes.
solution.py18 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def mergeTrees(root1, root2):
9 if not root1 and not root2:
10 return None
11 if not root1:
12 return root2
13 if not root2:
14 return root1
15 merged = TreeNode(root1.val + root2.val)
16 merged.left = mergeTrees(root1.left, root2.left)
17 merged.right = mergeTrees(root1.right, root2.right)
18 return mergedℹ
Complexity note: The time complexity is linear because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Merging trees requires careful handling of null nodes.
- 2Recursion is a powerful tool for tree traversal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.