← Questions
Construct a BST from its preorder traversal
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Mar 2026. It tests trees, bst and stacks.
You get the preorder traversal of a binary search tree whose values are all distinct. Rebuild the tree and return its root. Aim for linear time.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
bst_from_preorder(preorder: list[int]) -> TreeNode | None—TreeNodehasval,leftandright. An empty list returnsNone.
Example
preorder = [8, 5, 1, 7, 10, 12]
8
/ \
5 10
/ \ \
1 7 12
level order: [8, 5, 10, 1, 7, None, 12]
preorder = [] -> None
Constraints
-
0 <= len(preorder) <= 10^4. - Values are distinct integers, and the list is a valid BST preorder.
Clarifying questions
- Are values guaranteed distinct, and is the input guaranteed to be a valid preorder of some BST?
- Should invalid input be detected and reported?
- Is recursion depth a concern (a fully skewed tree of 10^4 nodes)?
What a strong answer covers
- The simple approach first: insert each value into a BST in order,
O(n^2)in the worst case, or find the split point between left and right subtrees with a scan or binary search,O(n log n). - The linear solution: recurse with an upper bound (or lower and upper bounds) and a shared index; a value goes into the current subtree only if it fits the bounds.
- Or the iterative stack version: keep a stack of ancestors, pop while the new value is larger, and attach it as the right child of the last popped node.
-
O(n)time andO(h)extra space, with a note on deep recursion for skewed input. - Tests: empty list, one node, strictly increasing and strictly decreasing input, the example above.
Follow-ups
- Rebuild the tree from its postorder traversal instead.
- How would you check that a given list is a valid BST preorder, without building the tree?
- Rebuild a general binary tree (not a BST) from preorder and inorder.
Where it's asked
- Meta · AI-enabled coding · Last asked Mar 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
trees · bst · stacks
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
