Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [1,null,8], root2 = [8,1] Output: [1,1,8,8]
Constraints:
[0, 5000].-105 <= Node.val <= 105When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method for combining elements from two sorted trees is straightforward. We extract all the numbers from both trees first. Then, we simply sort all the extracted numbers together to get the final result.
Here's how the algorithm would work step-by-step:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def getAllElementsBruteForce(root1, root2):
first_tree_elements = []
second_tree_elements = []
def inorderTraversal(root, elements_list):
if root:
inorderTraversal(root.left, elements_list)
elements_list.append(root.val)
inorderTraversal(root.right, elements_list)
# Extract elements from the first BST
inorderTraversal(root1, first_tree_elements)
# Extract elements from the second BST
inorderTraversal(root2, second_tree_elements)
combined_elements = first_tree_elements + second_tree_elements
# Sorting to combine the elements
combined_elements.sort()
return combined_elementsThe best way to merge two sorted binary search trees is to first extract their elements into sorted lists. Then, we can efficiently merge these two sorted lists into a single sorted list, which represents all elements in ascending order.
Here's how the algorithm would work step-by-step:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> list[int]:
first_tree_elements = []
second_tree_elements = []
def inorder_traversal(root: TreeNode, element_list: list[int]) -> None:
if root:
inorder_traversal(root.left, element_list)
element_list.append(root.val)
inorder_traversal(root.right, element_list)
# Traverse the first tree and store elements in sorted order.
inorder_traversal(root1, first_tree_elements)
# Traverse the second tree and store elements in sorted order.
inorder_traversal(root2, second_tree_elements)
merged_elements = []
first_index = 0
second_index = 0
# Merge the two sorted lists into a single sorted list.
while first_index < len(first_tree_elements) and second_index < len(second_tree_elements):
if first_tree_elements[first_index] <= second_tree_elements[second_index]:
merged_elements.append(first_tree_elements[first_index])
first_index += 1
else:
merged_elements.append(second_tree_elements[second_index])
second_index += 1
# Add any remaining elements from the first list.
while first_index < len(first_tree_elements):
merged_elements.append(first_tree_elements[first_index])
first_index += 1
# Add any remaining elements from the second list.
while second_index < len(second_tree_elements):
merged_elements.append(second_tree_elements[second_index])
second_index += 1
return merged_elements| Case | How to Handle |
|---|---|
| Both trees are empty (null) | Return an empty list as there are no elements to merge. |
| One tree is empty (null), the other is not | Return the sorted list of elements from the non-empty tree. |
| Both trees contain only one node | Merge the two single-element lists into a single sorted list. |
| One tree is extremely large, the other is small | Ensure the merge algorithm avoids excessive recursion or stack overflow issues and considers iterative merging approaches for scalability. |
| Trees contain duplicate values | The merging process should correctly handle duplicates, preserving all occurrences in the final sorted list. |
| Trees contain negative, zero, and positive values | The comparison and merging process should correctly order all elements including negative and zero values. |
| Trees are highly unbalanced or skewed | Inorder traversal should still be efficient, and the merge process should not degrade to quadratic time based on skewness. |
| Integer overflow during element comparison | Utilize a safe comparison method that avoids direct subtraction or addition to prevent potential overflow errors. |