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.
prehas up to 1000 keys, so a quadratic build still passes, but the expected solution is O(n).
- 1 <= n <= 10³, where n is the size of pre
- 1 <= pre[i] <= 10⁴
- All keys are distinct.
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).
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.
Approach
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?
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Attaching to the new top instead of the last node popped
while stack and stack[-1].data < key:
stack.pop()
stack[-1].right = nodewhile stack and stack[-1].data < key:
parent = stack.pop()
parent.right = nodeThe 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
while stack[-1].data < key:
parent = stack.pop()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.
Edge cases
[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.
[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.
Complexity
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).