Leetcode #1008: Construct Binary Search Tree from Preorder Traversal
In this guide, we solve Leetcode #1008 Construct Binary Search Tree from Preorder Traversal in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Stack, Tree, Binary Search Tree, Array, Binary Tree, Monotonic Stack
Intuition
We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.
Each element is pushed and popped at most once, yielding a linear-time scan.
Approach
Maintain a stack that is either increasing or decreasing, depending on the query.
When the invariant is broken, pop and resolve answers for those indices.
Steps:
- Scan elements once.
- Pop while the monotonic condition is violated.
- Use stack indices to update answers.
Example
Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Python Solution
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
def dfs(i: int, j: int) -> Optional[TreeNode]:
if i > j:
return None
root = TreeNode(preorder[i])
l, r = i + 1, j + 1
while l < r:
mid = (l + r) >> 1
if preorder[mid] > preorder[i]:
r = mid
else:
l = mid + 1
root.left = dfs(i + 1, l - 1)
root.right = dfs(l, j)
return root
return dfs(0, len(preorder) - 1)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.