LeetCode #1008 Medium

Construct BST from Preorder Traversal

Construct Binary Search Tree from Preorder Traversal is LeetCode 1008 (Medium). Given the preorder traversal of a binary search tree (node, then left subtree, then right subtree), rebuild the tree and return its root.

  • All values are distinct, and a valid BST always exists.
  • In a BST every value in a left subtree is smaller than the node, and every value in a right subtree is larger.

The array holds at most 100 values, so slower methods pass too, but an O(n) build is the expected answer.

Constraints
  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 1000
  • All the values of preorder are unique.
bstrecursionstack
Open on LeetCode ↗
02

Intuition

Preorder lists a node first, then all of its left subtree, then all of its right subtree. In a BST the left subtree holds exactly the values below the node, so as you read the array from left to right, the left subtree is the run of values that stay below the node's value.

So give each recursive call an upper limit, and let it take values only while they stay under it:

  • Left child's limit: the node's own value.
  • Right child's limit: the limit the node itself was given.

The first value over the limit is not lost: it belongs to an ancestor's right side, and the call that owns it picks it up. Each value is read once, so the build is O(n).

How to spot this pattern

Rebuilding a tree from one traversal works when the values themselves say where each one goes, as the BST order does here. Passing a bound down the recursion is the same tool as in Validate Binary Search Tree.

03

Approach

Try it first

Before reading on: for [8, 5, 1, 7, 10, 12], which values make up the left subtree of 8, and how could you tell while reading the array once, without searching ahead for the first value above 8?

1

Read the array with one shared index

Keep one index i into preorder, shared by every call. A call either builds a node from preorder[i] and moves i on, or builds nothing. Because the index is shared, each call starts exactly where the previous one stopped.

2

Return nothing when the next value does not fit

build(bound) returns None without reading when:

  • i has reached the end of the array, or
  • preorder[i] > bound: that value is too big for this subtree, and an ancestor will place it on its right.
3

Build the node, then both subtrees

Make a node from preorder[i] and move i on. Build node.left with the node's value as the bound, since only smaller values belong there. Then build node.right with the bound this call received: those values are above the node, but still have to fit wherever this node sits.

4

Start with no limit

Call build(infinity): the root takes the first value, and nothing in the tree is too big for it. Return the node it builds.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
▶3 i = 0
▶4 
▶5 def build(bound: float) -> Optional[TreeNode]:
▶6 nonlocal i
▶7 if i == len(preorder) or preorder[i] > bound:
▶8 return None
▶9 node = TreeNode(preorder[i])
▶10 i += 1
▶11 node.left = build(node.val)
▶12 node.right = build(bound)
▶13 return node
▶14 
▶15 return build(float("inf"))
preorder85171012i8nextbound8≤∞8 ≤ ∞ → new node, root
i0
bound∞
node8
The root is the first value, 8: preorder always lists a node before its subtrees. Its left subtree may only take values below 8; its right subtree gets no limit.
preorder85171012i85nextbound5≤85 ≤ 8 → new node, left of 8
i1
bound8
node5
5 fits under the bound 8, so it becomes the left child of 8. Its left subtree may only take values below 5; its right subtree gets the same bound, 8.
preorder85171012i851nextbound1≤51 ≤ 5 → new node, left of 5
i2
bound5
node1
1 fits under the bound 5, so it becomes the left child of 5. Its left subtree may only take values below 1; its right subtree gets the same bound, 5.
preorder85171012i851nextbound7>17 > 1 → left of 1 is empty
i3
bound1
The next value, 7, is above this call's bound 1, so it cannot go in the left subtree of 1: everything there must be below 1. Return nothing and leave 7 for a caller with a larger bound.
preorder85171012i851nextbound7>57 > 5 → right of 1 is empty
i3
bound5
The next value, 7, is above this call's bound 5, so it cannot go here; it belongs further up the tree. Return nothing and leave 7 for a caller with a larger bound.
preorder85171012i8517nextbound7≤87 ≤ 8 → new node, right of 5
i3
bound8
node7
7 fits under the bound 8, so it becomes the right child of 5. Its left subtree may only take values below 7; its right subtree gets the same bound, 8.
preorder85171012i8517nextbound10>710 > 7 → left of 7 is empty
i4
bound7
The next value, 10, is above this call's bound 7, so it cannot go in the left subtree of 7: everything there must be below 7. Return nothing and leave 10 for a caller with a larger bound.
preorder85171012i8517nextbound10>810 > 8 → right of 7 is empty
i4
bound8
The next value, 10, is above this call's bound 8, so it cannot go here; it belongs further up the tree. Return nothing and leave 10 for a caller with a larger bound.
preorder85171012i851710nextbound10≤∞10 ≤ ∞ → new node, right of 8
i4
bound∞
node10
10 faces no bound here, so it becomes the right child of 8. Its left subtree may only take values below 10; its right subtree gets no limit.
preorder85171012i851710nextbound12>1012 > 10 → left of 10 is empty
i5
bound10
The next value, 12, is above this call's bound 10, so it cannot go in the left subtree of 10: everything there must be below 10. Return nothing and leave 12 for a caller with a larger bound.
preorder85171012i85171012nextbound12≤∞12 ≤ ∞ → new node, right of 10
i5
bound∞
node12
12 faces no bound here, so it becomes the right child of 10. Its left subtree may only take values below 12; its right subtree gets no limit.
preorder85171012i85171012nextboundend12no values left → left of 12 is empty
i6
bound12
Every value has been placed, so the left of 12 stays empty. The call returns nothing.
preorder85171012i85171012nextboundend∞no values left → right of 12 is empty
i6
bound∞
Every value has been placed, so the right of 12 stays empty. The call returns nothing.
preorder85171012i85171012nextboundall 6 values placed → return root 8
root8
Done. Each value was read once, in order, and every node sits in the only spot its bounds allowed, so this is the BST with this preorder. Return the root.
05

Stack of open ancestors

The stack holds nodes that may still get a right child, with values decreasing from bottom to top. For each new value, pop every node smaller than it: the last one popped is its parent, and it goes on the right. If nothing is popped, it is the left child of the top node.

▶1class Solution:
▶2 def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
▶3 root = TreeNode(preorder[0])
▶4 stack = [root]
▶5 for val in preorder[1:]:
▶6 node = TreeNode(val)
▶7 parent = None
▶8 while stack and stack[-1].val < val:
▶9 parent = stack.pop()
▶10 if parent:
▶11 parent.right = node
▶12 else:
▶13 stack[-1].left = node
▶14 stack.append(node)
▶15 return root
06

Common pitfalls

Giving the right child the node's value as its bound

✗ Wrong
node.left = build(node.val)
node.right = build(node.val)
✓ Right
node.left = build(node.val)
node.right = build(bound)

The right side then only accepts values below the node, which belong on its left. On [8, 5, 1, 7, 10, 12], 7 is hung on the right of 8, and 10 and 12 are never placed.

Passing the index by value

✗ Wrong
def build(i, bound):
    ...
    node.left = build(i + 1, node.val)
    node.right = build(i + 1, bound)
✓ Right
nonlocal i  # one index shared by every call

The right subtree has to start where the left subtree stopped reading, and a copied index cannot know that. Both children start at i + 1, so values are read again: on [8, 5, 1, 7, 10, 12], 5 turns up as both children of 8.

07

Edge cases

Values only decreasing (or only increasing)

The tree is a chain of height n, so the recursion is n calls deep. With at most 100 values that is fine.

08

Complexity

Time
O(n)
Space
O(h)
Each value is read once, and each call does O(1) work besides its two child calls. The recursion is as deep as the tree is tall: O(log n) if balanced, O(n) for a chain.
09

Construct BST from Preorder Traversal FAQ

Why is the preorder alone enough to rebuild the tree?

For a general binary tree, preorder does not say where the left subtree ends, so you also need the inorder traversal. In a BST the values say it: the left subtree is exactly the values below the node, so preorder alone fixes the tree, and only one tree fits.

Are there simpler ways to build the tree?
  • Insert one by one: run normal BST insertion for each value. O(n²) when the input is sorted, since each insertion walks the whole chain.
  • Split at the first larger value: the root is preorder[0], the left subtree is everything before the first value above it, the right subtree is the rest. O(n²) with a linear scan, O(n log n) with binary search.

Both pass with 100 values, but the bound method is O(n).