All Elements in Two Binary Search Trees - Problem

You have two binary search trees containing integers, and your task is to merge all their elements into a single sorted list. This is like combining two sorted collections while maintaining the overall ascending order.

The Challenge: Given the root nodes of two BSTs (root1 and root2), return a list containing all integers from both trees sorted in ascending order.

Key Insight: Since BSTs naturally store elements in a way that supports in-order traversal to get sorted sequences, we can leverage this property for an efficient solution.

Example: If BST1 contains [2, 1, 4] and BST2 contains [1, 0, 3], the merged result should be [0, 1, 1, 2, 3, 4].

Input & Output

example_1.py โ€” Basic Case
$ Input: root1 = [2,1,4], root2 = [1,0,3]
โ€บ Output: [0,1,1,2,3,4]
๐Ÿ’ก Note: Tree 1 contains values [1,2,4] in sorted order, Tree 2 contains [0,1,3]. Merging gives [0,1,1,2,3,4].
example_2.py โ€” One Empty Tree
$ Input: root1 = [5,1,7,0,2], root2 = []
โ€บ Output: [0,1,2,5,7]
๐Ÿ’ก Note: When one tree is empty, result is just the in-order traversal of the non-empty tree.
example_3.py โ€” Both Empty
$ Input: root1 = [], root2 = []
โ€บ Output: []
๐Ÿ’ก Note: When both trees are empty, the result is an empty list.

Visualization

Tap to expand
214103In-order: [1, 2, 4]In-order: [0, 1, 3]Merged Result: [0, 1, 1, 2, 3, 4]
Understanding the Visualization
1
Walk Through Collections
Traverse each BST in-order to get naturally sorted sequences
2
Set Two Readers
Position one reader at the start of each sorted collection
3
Pick Smaller Item
Compare current items, always pick the smaller one for the merged list
4
Advance Reader
Move the reader forward in whichever collection we just took from
Key Takeaway
๐ŸŽฏ Key Insight: BSTs give us sorted sequences through in-order traversal, so we can merge them efficiently like two sorted lists without re-sorting!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O((m+n) log(m+n))

O(m+n) to traverse both trees plus O((m+n) log(m+n)) to sort the combined list

n
2n
โšก Linearithmic
Space Complexity
O(m+n)

Space needed to store all values from both trees in the result list

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in each tree is in the range [0, 5000]
  • -105 โ‰ค Node.val โ‰ค 105
  • Both trees are valid binary search trees
Asked in
Amazon 45 Google 32 Meta 28 Microsoft 22
35.7K Views
Medium Frequency
~15 min Avg. Time
1.2K 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