Construct Binary Search Tree from Preorder Traversal

medium

Given an integer array preorder — the preorder traversal of a binary search tree with distinct values — construct the BST and return its root.

The tree is returned in level-order (breadth-first), using null for missing children.

Hints

For a BST, preorder alone determines the tree — the ordering replaces inorder.
Simplest: insert each preorder value into the BST in order.
O(n): keep a monotonic stack — smaller value is the top's left child; larger value pops to its parent's right.

Common doubts

A BST's ordering tells you which side each value belongs on, so you don't need inorder to disambiguate.
The LAST node popped while the top is smaller than v — v becomes its right child.
A sorted (or reverse-sorted) preorder builds a degenerate chain, making inserts O(n) each — O(n^2) overall.

Interview follow-ups

Yes — recurse with an upper bound: build a node only while the next value is below the bound, giving O(n) without an explicit stack.
For a general tree you need both; a BST needs only preorder because ordering is the implicit second traversal.

Fun facts

  • A BST is uniquely determined by its preorder (or its postorder) alone — a property general binary trees don't share.
  • The monotonic-stack build is the same shape as 'next greater element' — ancestors are popped when a larger value arrives.

Asked at

AmazonMicrosoftBloomberg
Frequently Sometimes Occasionally
Example 1
Input: preorder = [8, 5, 1, 7, 10, 12]
Output: [8, 5, 10, 1, 7, null, 12]
Root 8; 5 and 10 are its children; 1, 7 under 5; 12 under 10.
Example 2
Input: preorder = [1, 3]
Output: [1, null, 3]
3 > 1, so it's the right child.
Constraints

- 1 <= preorder.length <= 100 - 1 <= preorder[i] <= 10^8 - All values are unique - preorder is a valid preorder of a BST

Solve this problem →