All Elements in Two Binary Search Trees Problem
Description
LeetCode Problem 1305.
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:
- The number of nodes in each tree is in the range
[0, 5000]. -10^5 <= Node.val <= 10^5
Solution
Approach: In-Order Traversal and Merge
An in-order traversal (left subtree, node, right subtree) of a binary search tree visits its values in ascending order. So one traversal of each tree gives two sorted lists, and we never need to sort.
Then merge them like the last step of merge sort: keep an index into each list, repeatedly append the smaller of the two front values and advance that index, and when one list runs out, append the rest of the other. Values that appear in both trees end up next to each other, as in Example 2 ([1,1,8,8]).
Either tree can be empty; its list is then empty, and the merge just copies the other one.
Complexity: O(m + n) time for trees with m and n nodes, and O(m + n) space for the lists (plus the recursion, which is as deep as the taller tree).
class Solution:
def getAllElements(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> List[int]:
def inorder(node, out):
# In-order traversal of a BST visits the values in ascending order.
if node:
inorder(node.left, out)
out.append(node.val)
inorder(node.right, out)
return out
a, b = inorder(root1, []), inorder(root2, [])
# Merge the two sorted lists, as in merge sort.
ans = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
ans.append(a[i])
i += 1
else:
ans.append(b[j])
j += 1
ans += a[i:]
ans += b[j:]
return ans