Construct Binary Search Tree from Preorder Traversal - Problem
Given an array of integers representing the preorder traversal of a Binary Search Tree (BST), your task is to reconstruct and return the original BST.
In a BST, for every node:
- All values in the left subtree are strictly less than the node's value
- All values in the right subtree are strictly greater than the node's value
A preorder traversal visits nodes in this order: root โ left subtree โ right subtree
Example: If preorder = [8, 5, 1, 7, 10, 12], this represents:
8 / \ 5 10 / \ \ 1 7 12
You need to reconstruct this tree structure and return the root node. It's guaranteed that a valid BST can always be constructed from the given preorder sequence.
Input & Output
example_1.py โ Standard BST
$
Input:
preorder = [8,5,1,7,10,12]
โบ
Output:
[8,5,10,1,7,null,12]
๐ก Note:
The preorder traversal represents a BST where 8 is root, 5 and 10 are children of 8, and so on. The output shows the tree in level-order format.
example_2.py โ Single Node
$
Input:
preorder = [1]
โบ
Output:
[1]
๐ก Note:
A tree with only one node - the root node with value 1.
example_3.py โ Right Skewed Tree
$
Input:
preorder = [1,2,3,4]
โบ
Output:
[1,null,2,null,3,null,4]
๐ก Note:
Since each value is greater than the previous, each node only has a right child, creating a right-skewed tree.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Bounds
Start with root and infinite bounds (-โ, +โ)
2
Place Node
If current value fits bounds, create node and advance index
3
Update Bounds
Left child gets (min, current), right child gets (current, max)
4
Recurse
Continue with updated bounds for each subtree
Key Takeaway
๐ฏ Key Insight: Using bounds eliminates the need to scan for subtree boundaries. Each recursive call constrains valid values, allowing sequential processing of the preorder array in optimal O(n) time.
Time & Space Complexity
Time Complexity
O(nยฒ)
For each of n nodes, we scan through remaining elements to find subtree boundaries
โ Quadratic Growth
Space Complexity
O(n)
Recursion stack depth can be O(n) in worst case (skewed tree)
โก Linearithmic Space
Constraints
- 1 โค preorder.length โค 100
- 1 โค preorder[i] โค 1000
- All values in preorder are unique
- The input represents a valid preorder traversal of a BST
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code