Case 1: Normal Trees with Elements
When both binary search trees contain multiple elements, we can perform an in-order traversal on each tree. This traversal gives a sorted array of elements for each BST. Next, merge these two sorted arrays into one using the standard merging technique from merge sort.
The final step is to build a balanced BST from the merged sorted array. This is done by picking the middle element as the root and recursively building the left and right subtrees. This ensures that the tree remains balanced.
For example, Tree1 = [2, 1, 4] gives [1, 2, 4] and Tree2 = [3, 6] gives [3, 6]. Merging them: [1, 2, 3, 4, 6]. Then build a balanced BST using this array.
Case 2: One Tree is Empty
If one of the trees is empty, we can skip traversal and merging for that tree. Simply return the other tree as it is already a valid BST. There’s no need to perform any merging or reconstruction.
For example, Tree1 = [] and Tree2 = [1], the merged result is just [1], which itself is a BST.
Case 3: Both Trees are Empty
If both trees are empty, the result is also an empty tree. There are no elements to process or build into a BST.
This is the base case in recursive solutions and can be handled easily by returning null
or an empty list.
Case 4: Trees with Disjoint or Overlapping Ranges
If the values in the trees are completely disjoint (e.g., all values in Tree1 are less than those in Tree2), the merged array remains sorted with no overlap. If there’s an overlap, the merge step ensures the final array maintains sorted order.
For example, Tree1 = [5, 3, 7, 2, 4, 6, 8] and Tree2 = [10, 9, 11] gives merged array [2, 3, 4, 5, 6, 7, 8, 9, 10, 11], and this is used to construct the final balanced BST.
Case 5: Skewed Trees
In cases where one or both trees are skewed (all nodes are either on the left or right), the traversal step will still generate sorted arrays. Hence, the merge and build steps work the same way.
The final BST after construction will be balanced, even if input trees were not.