All Elements in Two Binary Search Trees

Given the roots of two binary search trees, root1 and root2, return a list containing every value from both trees sorted in ascending order.

30:00

All Elements in Two Binary Search Trees
medium
Free written solution
Topics
Companies

Given the roots of two binary search trees, root1 and root2, return a list containing every value 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]
Constraints:
  • The number of nodes in each tree is in the range [0,5000][0, 5000].

  • −105≤Node.val≤105-10^5 \leq \text{Node.val} \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root1":[2,1,4],"root2":[1,0,3]}

Both trees are BSTs, so an inorder walk of each yields sorted values. Walk them side by side and merge, like merging two sorted lists.

tree 1

214

stack 1

empty

tree 2

103

stack 2

empty

compare tops

-

out (0)

[]

from tree 1from tree 2just taken / stack top
Variables
VariableValue
top1empty
top2empty
len(out)0
DepthFunction Call
Stack empty
0/11