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
Visualization
Time & Space Complexity
O(m+n) to traverse both trees plus O((m+n) log(m+n)) to sort the combined list
Space needed to store all values from both trees in the result list
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