Merge Two BSTs into Array

LeetCode

LeetCode: https://leetcode.com/problems/all-elements-in-two-binary-search-trees/

Return a sorted array containing all elements from two BSTs.

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
2
0
4
1
6
2
|
3
1
4
3
5
5
6
a=[2, 4, 6]
b=[1, 3, 5]
Step 1 / 3
Step 1:
Extract two inorder arrays.
Focus: select @ [0, 3]