GeeksforGeeks Medium

Construct BST from Given Keys (Preorder)

Construct BST from Given Keys (Preorder) is a GFG problem (Medium). On the practice site it is listed as Preorder to BST.

You get an array pre holding the preorder traversal of a binary search tree: each node, then its whole left subtree, then its whole right subtree. The keys are distinct. Build the tree with preToBST(pre) and return its root; the judge prints it level by level, with N for a missing child.

  • In a BST, every key in a node's left subtree is smaller than the node and every key in its right subtree is larger.
  • pre has up to 1000 keys, so a quadratic build still passes, but the expected solution is O(n).
Constraints
  • 1 <= n <= 10³, where n is the size of pre
  • 1 <= pre[i] <= 10⁴
  • All keys are distinct.
bstrecursion
Open on GeeksforGeeks ↗
02

Intuition

Read the keys left to right and keep a stack of nodes that may still get a right child, deepest on top. Their keys get smaller from bottom to top.

  • Key smaller than the top: preorder lists a node's left subtree straight after the node, so the key is the top's left child.
  • Key larger than the top: the top's left side is finished. Pop every node smaller than the key; the last one popped is its parent, and the key is that node's right child.

Push each new node, since it may get children of its own. Every node is pushed once and popped at most once, so the whole build is O(n).

How to spot this pattern

Rebuilding a tree from one traversal is possible only when the keys say where each one goes, as the BST order does. A stack that holds a decreasing run of open nodes is the same tool as a monotonic stack.

03

Approach

Try it first

Before reading on, take [40, 30, 35, 80, 100]. When 35 arrives, which earlier node is its parent, and why is it not 40? When 80 arrives, which nodes can never get another child?

1

Start with the root on the stack

The first key in preorder is always the root. Make its node and push it: it is the only node so far, and it can still take children on both sides.

2

Attach a smaller key on the left

For each next key, compare it with the node on top of the stack. If the key is smaller, make it the top's left child. The top is always the node made from the previous key, so it has no children yet, and a smaller key right after a node in preorder starts that node's left subtree.

3

Climb up for a larger key

If the key is larger, pop while the stack is not empty and the top is smaller than the key, remembering the last node popped. That node is the deepest open node smaller than the key, so the key becomes its right child. Each popped node already has its right child or never will, so dropping it loses nothing.

4

Push the new node

Push the node just attached, whichever side it went on. It may still get a left or right child from the keys that follow. After the last key, return the root.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def preToBST(self, pre):
▶3 root = Node(pre[0])
▶4 stack = [root]
▶5 for key in pre[1:]:
▶6 node = Node(key)
▶7 if key < stack[-1].data:
▶8 stack[-1].left = node
▶9 else:
▶10 while stack and stack[-1].data < key:
▶11 parent = stack.pop()
▶12 parent.right = node
▶13 stack.append(node)
▶14 return root
preorder40key30358010040stack40top40 comes first → it is the root, push it
root40
stack[40]
Preorder always lists the root first, so 40 is the root. It goes on the stack because it can still take a left and a right child.
preorder4030key35801004030stack4030top30 is smaller than 40 → left child of 40
key30
top40bigger than the key
Preorder lists a node's left subtree right after the node. The top node 40 has no child yet and 30 is smaller, so 30 is its left child. Push 30: it may get children too.
preorder403035key801004030stack4030top30 is smaller than 35 → pop 30
key35
top30smaller than the key
35 is bigger than 30, so it belongs somewhere to the right of 30, and everything under 30's left side is done. Pop it and remember it as the parent so far; a node further down the stack may still be smaller than 35.
preorder403035key80100403035stack4035top40 is bigger, stop → 35 is right child of 30
key35
last popped30
The new top 40 is bigger than 35, so popping stops there. The last node popped, 30, is the deepest open node smaller than 35, so 35 is its right child. Push 35.
preorder40303580key100403035stack4035top35 is smaller than 80 → pop 35
key80
top35smaller than the key
80 is bigger than 35, so it belongs somewhere to the right of 35, and everything under 35's left side is done. Pop it and remember it as the parent so far; a node further down the stack may still be smaller than 80.
preorder40303580key100403035stack40top40 is smaller than 80 → pop 40
key80
top40smaller than the key
80 is bigger than 40, so it belongs somewhere to the right of 40, and everything under 40's left side is done. Pop it and remember it as the parent so far; a node further down the stack may still be smaller than 80.
preorder40303580key10040303580stack80topstack is empty → 80 is right child of 40
key80
last popped40
Every node on the stack was smaller, so the stack is now empty. The last node popped, 40, is the deepest open node smaller than 80, so 80 is its right child. Push 80.
preorder40303580100key40303580stack80top80 is smaller than 100 → pop 80
key100
top80smaller than the key
100 is bigger than 80, so it belongs somewhere to the right of 80, and everything under 80's left side is done. Pop it and remember it as the parent so far; a node further down the stack may still be smaller than 100.
preorder40303580100key40303580100stack100topstack is empty → 100 is right child of 80
key100
last popped80
Every node on the stack was smaller, so the stack is now empty. The last node popped, 80, is the deepest open node smaller than 100, so 100 is its right child. Push 100.
preorder4030358010040303580100stack100topdone → level order 40 30 80 N 35 N 100
root40
level order40 30 80 N 35 N 100
Every key is placed, so return the root 40. Printed level by level with N for a missing child, the tree reads 40 30 80 N 35 N 100. Each node went on the stack once and came off at most once.
05

Common pitfalls

Attaching to the new top instead of the last node popped

✗ Wrong
while stack and stack[-1].data < key:
    stack.pop()
stack[-1].right = node
✓ Right
while stack and stack[-1].data < key:
    parent = stack.pop()
parent.right = node

The node left on top is larger than the key, so the key belongs in its left subtree, never as its right child. On [40, 30, 35, 80, 100], 35 pops 30 and is then hung on the right of 40, although 35 is smaller than 40. When 80 pops everything, the same line crashes on the empty stack.

Popping without checking that the stack is empty

✗ Wrong
while stack[-1].data < key:
    parent = stack.pop()
✓ Right
while stack and stack[-1].data < key:
    parent = stack.pop()

A key larger than every key so far pops the root too, and the next stack[-1] fails on an empty stack. [10, 20] crashes on its second key.

06

Edge cases

Keys only increasing, e.g. [10, 20, 30]

Each key pops the single node on the stack and becomes its right child, so the tree is a right chain and the stack never holds more than one node.

Keys only decreasing, e.g. [30, 20, 10]

Every key is a left child and nothing is popped, so the stack grows to n nodes. That is heap memory, not recursion, so 1000 keys cause no stack overflow.

07

Complexity

Time
O(n)
Space
O(n)
Each node is pushed once and popped at most once, so the inner loop runs at most n times over the whole build. The stack holds at most n nodes (a left chain); the tree itself is O(n) too.
08

Construct BST from Given Keys (Preorder) FAQ

Is this the same as Construct Binary Search Tree from Preorder Traversal?

Yes, that problem (number 1008) is the same task, with at most 100 keys, a val field and the method bstFromPreorder; that page builds the tree by recursion with an upper bound. Here the node field is data, up to 1000 keys arrive, and the stack build on this page is what the practice site expects.

Why is the last node popped the right parent?

The stack holds open nodes with keys falling from bottom to top. The popped nodes are exactly the open nodes smaller than the key, and the last popped is the largest of them. The key must go in that node's right subtree, and the node has no right child yet (it was still open), so the key goes right there.

Is inserting the keys one by one good enough?

It is correct: plain BST insertion of the keys in preorder order rebuilds the same tree. Each insertion walks from the root, so it costs O(n · h), up to about 500,000 steps for 1000 sorted keys. That passes, but the stack build is O(n).