Problem Description
Implement the BSTIterator class that supports bidirectional iteration over the in-order traversal of a binary search tree (BST). The iterator is initialized with a pointer set before the smallest element, and provides next() and prev() methods to move right and left, respectively, in the sorted order of the BST nodes.
Key Insights
- In-order traversal of a BST produces a sorted sequence of elements.
- Storing the in-order values in a list allows O(1) time for both next() and prev() accesses.
- By initializing the pointer before the first element, the first call to next() will return the smallest element.
- The approach efficiently handles the given constraints by precomputing the traversal.
Space and Time Complexity
Time Complexity: O(n) for the initial in-order traversal; O(1) for each next() and prev() call.
Space Complexity: O(n) for storing the in-order list of node values.
Solution
The solution involves performing an in-order traversal of the given BST during initialization to store all node values in a sorted list. A pointer (index) is then used to navigate through the list. The pointer starts at -1 to represent a position before the first element. Each call to next() increments the pointer and returns the associated value, while each call to prev() decrements it.
An alternative follow-up approach could avoid precomputing by using a stack to maintain the traversal state on-the-fly, but for simplicity and efficiency, the precomputed list is used.