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
All Elements in Two Binary Search Trees INPUT BST 1: root1 = [2,1,4] 2 1 4 BST 2: root2 = [1,0,3] 1 0 3 BST Property: Left < Node < Right Inorder gives sorted: 1,2,4 and 0,1,3 ALGORITHM STEPS 1 Inorder Traversal BST1 Traverse: L-Root-R --> [1,2,4] 2 Inorder Traversal BST2 Traverse: L-Root-R --> [0,1,3] 3 Merge Two Sorted Lists Two-pointer technique 4 Build Result Array Compare and append smaller Merge Process: List1: [1,2,4] List2: [0,1,3] 0<1 --> add 0 1=1 --> add 1,1 2<3 --> add 2 3<4 --> add 3 remaining --> add 4 FINAL RESULT Merged Sorted Array: 0 1 1 2 3 4 Output: [0,1,1,2,3,4] OK - Sorted! Complexity: Time: O(m+n) Space: O(m+n) m,n = tree sizes Key Insight: Inorder traversal of a BST always produces a sorted sequence. By performing inorder traversal on both trees, we get two sorted lists. Merging two sorted lists is a classic O(m+n) operation using two pointers. TutorialsPoint - All Elements in Two Binary Search Trees | Inorder Traversal + Merge Approach
Asked in
Amazon 38 Google 25 Microsoft 20 Facebook 15
125.0K Views
Medium Frequency
~18 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen