Skip to content

Merge Two BSTs into Array

LeetCode

01 · Question

Return a sorted array containing all elements from two BSTs.

02 · Solution

Reference solution

1def getAllElements(root1: Optional[TreeNode], root2: Optional[TreeNode]) -> list[int]:
2 def inorder(root: Optional[TreeNode]) -> list[int]:
3 if not root:
4 return []
5 return inorder(root.left) + [root.val] + inorder(root.right)
6 a = inorder(root1)
7 b = inorder(root2)
8 i = j = 0
9 res = []
10 while i < len(a) and j < len(b):
11 if a[i] <= b[j]:
12 res.append(a[i]); i += 1
13 else:
14 res.append(b[j]); j += 1
15 res.extend(a[i:]); res.extend(b[j:])
16 return res