DSA interview question
A config service stores a BST as just its preorder sequence and must rebuild the exact tree. For a BST, preorder alone is enough, because the ordering tells each value where it belongs. Inserting the values one by one works but is O(n²) on skewed trees. The O(n) method passes an upper bound: each call builds a subtree from the next preorder values as long as they're below the bound. A node's left subtree uses the node's own value as its bound, and its right subtree inherits the parent's bound.
Example: [8, 5, 1, 7, 10, 12] → [8, 5, 10, 1, 7, null, 12].
TreeNode* bstFromPreorder(const vector<int>& preorder); // distinct values
| Input (preorder) | Output (level order) | Explanation |
|---|---|---|
[8, 5, 1, 7, 10, 12] | [8, 5, 10, 1, 7, null, 12] | |
[4, 2, 1, 3, 6, 5, 7] | [4, 2, 6, 1, 3, 5, 7] | |
[1, 3] | [1, null, 3] | |
[5] | [5] | |
[] | [] |
(Confirm: values are distinct and the sequence is a valid BST preorder.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in