Problem Description
Given two binary search trees, root1 and root2, return a single list that contains all the integers from both trees in ascending order.
Key Insights
- In-order traversal of a BST produces a sorted list.
- Perform in-order traversal on both trees separately.
- Merge the two sorted lists into one sorted list.
- Handle edge cases where one or both trees might be empty.
Space and Time Complexity
Time Complexity: O(n1 + n2), where n1 and n2 are the number of nodes in root1 and root2 respectively, due to performing in-order traversals and merging. Space Complexity: O(n1 + n2) for storing the elements from both trees.
Solution
The solution involves two main steps:
- Traverse each binary search tree using an in-order traversal to get a sorted list of values.
- Merge the two sorted lists using the two-pointer technique to produce one final sorted list.
Data Structures and Algorithms used:
- Recursion for in-order traversal.
- Two-pointer technique for merging two sorted arrays. This approach efficiently leverages the BST property and sorting of individual traversals.