Construct Binary Search Tree from Preorder Traversal
LeetCode 1008 · Medium · solution, intuition & step-by-step walkthrough
Pre-order index + upper bound recursion.
This is how I solved Construct Binary Search Tree from Preorder Traversal (LeetCode 1008), a medium problem from the Construction / Serialization pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Consume the pre-order list left to right. Each value becomes a node, its left subtree takes the following values smaller than it, and its right subtree takes values up to the ancestor's bound.
Approach
- 1
dfs(bound): stop if the list is used up or the next value exceeds bound.
- 2
Create a node and advance the index.
- 3
left = dfs(node.val); right = dfs(bound).
How I solved it
Bounded pre-order recursionPythonO(n) time
class Solution:
def bstFromPreorder(self, preorder):
self.i = 0
def dfs(preorder, upperBound):
if self.i == len(preorder) or preorder[self.i] > upperBound:
return None
root = TreeNode(preorder[self.i])
self.i += 1
root.left = dfs(preorder, root.val)
root.right = dfs(preorder, upperBound)
return root
return dfs(preorder, float("inf"))Construct Binary Search Tree from Preorder Traversal — FAQ
What is the intuition behind Construct Binary Search Tree from Preorder Traversal?
Consume the pre-order list left to right. Each value becomes a node, its left subtree takes the following values smaller than it, and its right subtree takes values up to the ancestor's bound.
How do you solve Construct Binary Search Tree from Preorder Traversal (LeetCode 1008)?
1. dfs(bound): stop if the list is used up or the next value exceeds bound. 2. Create a node and advance the index. 3. left = dfs(node.val); right = dfs(bound).
What is the time and space complexity of Construct Binary Search Tree from Preorder Traversal?
Time: O(n). Space: O(h). (Accepted approach: Bounded pre-order recursion.)
What are common mistakes in Construct Binary Search Tree from Preorder Traversal?
Inserting values one by one is O(n²) for sorted input.