All Elements in Two Binary Search Trees - Problem
Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.
A binary search tree (BST) is a tree where for every node, all values in the left subtree are smaller and all values in the right subtree are larger than the node's value.
Constraints:
- The number of nodes in each tree is in the range
[0, 5000] -105 ≤ Node.val ≤ 105
Input & Output
Example 1 — Basic Two BSTs
$
Input:
root1 = [2,1,4], root2 = [1,0,3]
›
Output:
[0,1,1,2,3,4]
💡 Note:
BST1 inorder: [1,2,4], BST2 inorder: [0,1,3]. Merged result: [0,1,1,2,3,4]
Example 2 — One Empty Tree
$
Input:
root1 = [5,1,7], root2 = []
›
Output:
[1,5,7]
💡 Note:
BST1 inorder: [1,5,7], BST2 is empty. Result is just BST1's values in sorted order.
Example 3 — Single Node Trees
$
Input:
root1 = [1], root2 = [8]
›
Output:
[1,8]
💡 Note:
BST1 has [1], BST2 has [8]. Combined sorted: [1,8]
Constraints
- The number of nodes in each tree is in the range [0, 5000]
- -105 ≤ Node.val ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input BSTs
Two binary search trees with sorted property
2
Extract Values
Get all values maintaining sort order
3
Merge Result
Combined sorted array with all elements
Key Takeaway
🎯 Key Insight: BST inorder traversal naturally gives sorted order - use this property to avoid unnecessary sorting!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code