PPractick

DSA interview question

Merge Two BSTs into a Sorted List

Hard · Data structures · Topics: bst, stack, inorder

The problem

Two shops keep their product IDs in separate BSTs, and a combined catalogue needs all IDs from both trees in sorted order. Each BST's inorder traversal is already sorted, so the task is merging two sorted streams. Materialising both inorder lists and merging works with O(n + m) extra memory. The elegant version runs two iterative inorder traversals in lockstep, each with its own stack, and always advances the one whose next value is smaller. That needs only O(h₁ + h₂) extra memory.

Example: [2, 1, 4] and [1, 0, 3] → [0, 1, 1, 2, 3, 4].

Function signature

vector<int> getAllElements(TreeNode* root1, TreeNode* root2);

Test cases

Input (tree1, tree2)OutputExplanation
([2, 1, 4], [1, 0, 3])[0, 1, 1, 2, 3, 4]
([1, null, 8], [8, 1])[1, 1, 8, 8]Duplicates across trees are kept
([], [5, 1, 7])[1, 5, 7]
([3], [])[3]
([], [])[]

(Confirm: each tree is a valid BST; values may repeat across the two trees.)

How interviewers phrase it

Clarifying questions to ask

  1. Keep duplicates? (Yes.)
  2. Is extra memory limited? (That decides between merging arrays and merging with stacks.)
  3. Do I return a list or build a new BST? (A list here.)

Follow-ups to expect

  1. "Simplest approach?"
  2. "How do the two stacks work?"
  3. "Why is it still linear?"
  4. "How would you build a balanced BST from the merged list?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in