Construct Binary Search Tree from Preorder Traversal (LeetCode 1008): Solution and Explanation

Medium
Array
Stack
Tree
Binary Search Tree
Monotonic Stack
Binary Tree

You get the preorder traversal of a BST with distinct values. Rebuild the tree and return its root.

Intuition

Preorder lists a node before its subtrees, so the first value is the root. The values that follow are the whole left subtree (all smaller than the root) and then the whole right subtree (all larger).

You could find the split point with a scan and recurse on both halves, but that is O(n^2) on a sorted input. A better question is: while reading values left to right, how do we know when a subtree is finished?

A subtree is finished as soon as the next value is too large for it. The left subtree of node v takes values below v; the right subtree of v takes values below whatever bound v itself had. Passing that upper bound down lets one pointer read the array exactly once.

Approach: Recursion with an upper bound

  1. Keep a shared index i into preorder.
  2. build(bound): if i has reached the end or preorder[i] is greater than bound, return null because this slot stays empty.
  3. Otherwise create a node from preorder[i] and advance i.
  4. Build the left child with bound node.val and the right child with the same bound this call received, then return the node.
  5. Call build(infinity) for the root.

Step-by-step example

preorder = [8,5,1,7,10,12]
  1. build(inf) takes 8. Its left call has bound 8 and takes 5; 5's left call has bound 5 and takes 1.
  2. 1's children have bounds 1 and 5; the next value 7 is above both, so 1 stays a leaf. Back at 5, its right call has bound 8 and takes 7.
  3. 7's children have bounds 7 and 8, and 10 is too big for both, so 7 is a leaf and the whole left subtree of 8 closes. 8's right call has bound inf and takes 10, and 10's right call takes 12.
  4. Result: [8,5,10,1,7,null,12].

Code: Python, Java, C++

1class Solution:
2    def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
3        self.i = 0
4        def build(bound):
5            if self.i == len(preorder) or preorder[self.i] > bound:
6                return None
7            node = TreeNode(preorder[self.i])
8            self.i += 1
9            node.left = build(node.val)
10            node.right = build(bound)
11            return node
12        return build(float('inf'))
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each value is read once to create a node, and each call that returns null does O(1) work; there are at most n + 1 of those.

Space

O(n)

The recursion depth equals the tree height, which is n for a sorted (chain) input.

Other approaches

Monotonic stack (time O(n), space O(n))

Iterate over preorder, keeping a stack of nodes whose right child is still open. Pop while the top is smaller than the new value; the last popped node gets the new value as its right child, otherwise the new value is the left child of the top.

Insert one by one (time O(n^2) worst case, space O(n))

Insert each value into a BST starting from the root. Simple, but each insert walks from the root, so a sorted input costs O(n^2).

Sort for inorder, then rebuild (time O(n log n), space O(n))

Sorting gives the inorder traversal, and preorder plus inorder determines a binary tree. It works but ignores the BST property that makes the bound method linear.

Common mistakes

  • Giving the right child the parent's value as a bound. The right subtree is bounded by the parent's own upper bound, not by the parent.
  • Using a local index that is not shared between calls. The pointer must advance across the whole recursion, so it needs to be a field, a reference, or a captured variable.
  • Forgetting to reset a class-level index between calls if the same Solution object is reused.
  • Splitting with a linear scan at every level, which turns sorted inputs into O(n^2).

Frequently asked questions

Why is only an upper bound needed, not a lower bound too?

Preorder guarantees that values for a subtree come only after its parent. Any value that reaches a slot is already larger than the lower limit for that slot, because smaller values were consumed by earlier left subtrees. Only the upper end needs checking.

Why is the right child's bound the parent's bound?

Every node in the right subtree of v must be larger than v and also fit wherever v fits. v's own bound is the tightest upper limit coming from its ancestors.

Is the stack version faster?

Both are O(n). The stack version avoids recursion, which matters only if inputs could be very deep; here the length is at most 100.

Is the tree unique?

Yes. With distinct values, a preorder traversal determines exactly one BST.