Construct BST from Given Keys (Preorder)
Build the BST whose preorder traversal is the given key sequence.
Open on GeeksforGeeks ↗Intuition
In a BST, order alone determines structure: each preorder value slots into the unique valid position. Recurse with (min, max) bounds — a value inside the current bounds belongs here; outside, it belongs to an ancestor's other side. One pass, no searching.
Preorder plus the BST ordering property is enough — no inorder array required. Each recursive call carries a valid (lo, hi) window, and a value outside it belongs to an ancestor's other branch, which is exactly the signal to stop and return.
Approach
Bounds encode the ancestors
Every left turn tightens the max; every right turn tightens the min. The next key is consumed by the first frame whose bounds admit it.
Single pointer, O(n)
The recursion never re-reads a key — compare with bounds, either consume or return None up the stack.
Contrast with insert-one-by-one
Repeated BST insertion is O(n·h); the bounds trick is linear.
Solution & live demo
Common pitfalls
Sorting to recover the inorder array
inorder = sorted(pre) # then the two-array construction
if not (lo < pre[idx[0]] < hi):
return NoneCorrect but O(n log n) plus an index map, when the BST property already encodes the ordering. The bounds check does the same work in O(n) with no extra structure.
Passing the index by value
def build(i, lo, hi):
node.left = build(i + 1, lo, val)idx = [0] ... val = pre[idx[0]]; idx[0] += 1
The left subtree consumes an unknown number of preorder entries, so the right subtree's start index isn't computable from i. A shared mutable cursor advances correctly without that arithmetic.
Using inclusive bounds
if not (lo <= pre[idx[0]] <= hi):
if not (lo < pre[idx[0]] < hi):
The bounds are the ancestor values themselves, which are already placed in the tree. Inclusive comparison lets a duplicate of an ancestor be re-inserted below it, corrupting the structure.
Edge cases
Degenerate right chain — bounds still route each key correctly.
Return None.