Problem Description
Design an iterator for a binary search tree (BST) that returns nodes during an in-order traversal. Implement the BSTIterator class with the following functionalities:
- BSTIterator(TreeNode root): Initializes the iterator. The pointer is set to a value smaller than the smallest element.
- boolean hasNext(): Returns true if there are further nodes in the traversal.
- int next(): Advances the iterator to the next node and returns its value.
Key Insights
- Use an iterative in-order traversal strategy with a stack.
- In-order traversal for BST yields sorted order.
- Pre-load the stack with all left descendants from the root.
- After returning a node, process its right subtree by pushing its left branch.
- This method maintains an average time complexity of O(1) per operation and uses O(h) memory, where h is the tree height.
Space and Time Complexity
Time Complexity: O(1) on average per operation (amortized) Space Complexity: O(h), where h is the height of the tree
Solution
We use a stack to simulate an in-order traversal. The process involves initially pushing all left-child nodes from the root into the stack. For each call to next(), we pop the top element (the current smallest node) and then push all the left descendents of the node's right child. This ensures that the next smallest element is always at the top of the stack. The hasNext() function then simply checks if the stack is non-empty.