Problem Description
Given an array of integers representing the preorder traversal of a binary search tree (BST), construct the BST and return its root. Recall that in a BST, for every node, all nodes in the left subtree have values strictly less than the node’s value and all nodes in the right subtree have values strictly greater. The preorder traversal visits nodes in the order: root, left subtree, then right subtree.
Key Insights
- The preorder sequence always starts with the root of the tree.
- For any node, elements in the left subtree must be less than the node’s value, while elements in the right subtree must be greater.
- Use recursion with bounds (or an iterative approach with a stack) to determine where a new value fits in the BST.
- Maintain an index into the preorder array to build the tree sequentially.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes since each node is processed exactly once. Space Complexity: O(n) in the worst case due to the recursion call stack (for a skewed tree).
Solution
We can solve this problem using a recursive approach. The recursive function will have lower and upper bounds which restrict the valid range for node values at each stage. Starting with the entire range (-∞, +∞), we process each value in the preorder list in order. If the next value lies within the bounds, it is accepted as a node. We then recursively construct the left subtree with an updated upper bound (current node's value) and the right subtree with an updated lower bound (current node's value). This ensures that the BST property is maintained throughout.
The key data structure used is the recursion call stack, which inherently manages the bounds for a valid BST construction. The algorithm processes each element of the preorder sequence exactly once, leading to optimal time complexity.