#1008
Construct Binary Search Tree from Preorder Traversal
MediumArrayStackTreeBinary Search TreeMonotonic StackBinary TreeRecursionTree Traversals
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses the properties of the preorder traversal and recursion to build the BST efficiently. By maintaining a range for valid values, we can decide where to place each node without needing to traverse the tree repeatedly.
⚙️
Algorithm
3 steps- 1Step 1: Define a recursive function that takes the current bounds (lower and upper) for valid node values.
- 2Step 2: If the current value is within bounds, create a new node and recursively build the left and right subtrees with updated bounds.
- 3Step 3: Return the constructed node.
solution.py22 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def bst_from_preorder(preorder):
9 def helper(lower, upper):
10 nonlocal index
11 if index == len(preorder):
12 return None
13 val = preorder[index]
14 if val < lower or val > upper:
15 return None
16 index += 1
17 root = TreeNode(val)
18 root.left = helper(lower, val)
19 root.right = helper(val, upper)
20 return root
21 index = 0
22 return helper(float('-inf'), float('inf'))ℹ
Complexity note: The time complexity is O(n) since we process each element exactly once. The space complexity is O(n) due to the recursive call stack in the worst case.
- 1The preorder traversal gives us the root first, allowing us to build the tree recursively.
- 2Maintaining bounds for valid node values helps in deciding where to place each node efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.