Merging 2 Binary Search Trees
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Merging two binary search trees means combining their values into one valid search tree. The simplest practical strategy is to extract both trees in sorted order, merge the two sorted sequences, and build a balanced BST from the merged result. That gives a clean O(n + m) solution when both trees have n and m nodes.
Why Inorder Traversal Helps
An inorder traversal of a BST visits values in sorted order. That means each input tree can be converted into a sorted list with one traversal.
For example, if the trees contain these values:
- tree 1:
1, 3, 5, 7 - tree 2:
2, 4, 6, 8
their inorder traversals already produce the two sorted sequences you need.
Step 1: Traverse Both Trees
A minimal BST node and inorder helper in Python:
Now each tree can be flattened into a sorted list.
Step 2: Merge the Sorted Lists
Once you have two sorted lists, merge them exactly the way you would merge two sorted arrays in merge sort.
This step is linear in the total number of elements.
Step 3: Build a Balanced BST
If you insert the merged values one by one into a new BST, the result can become badly skewed. A better approach is to build a balanced tree from the sorted array by choosing the middle value as the root.
That produces a much healthier result for search performance.
Full Example
Output:
Complexity
The runtime is O(n + m) because:
- inorder traversal of both trees is linear
- merging the two sorted lists is linear
- building the balanced BST is linear
The straightforward version uses O(n + m) extra space for the merged arrays.
Alternative Approaches
You can reduce auxiliary storage by traversing both trees with stacks or iterators and streaming the merge, but that implementation is more complex. For interviews and ordinary application code, the array-based approach is usually the clearest correct answer.
Common Pitfalls
A common mistake is inserting merged values into a new BST one by one. That preserves ordering but can produce a badly unbalanced tree.
Another mistake is forgetting that inorder traversal is sorted only because the input is a valid BST. If one tree violates BST rules, the whole merge logic breaks.
A third issue is ignoring duplicates. Decide whether duplicates should be preserved, removed, or counted differently before you finalize the merge logic.
Summary
- Inorder traversal turns each BST into a sorted list
- Merge the two sorted lists in linear time
- Build a balanced BST from the merged sorted values
- The simple solution runs in
O(n + m)time withO(n + m)extra space - Avoid rebuilding the final BST by repeated insertion if you want good balance

