Problem Description
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root)Initializes an object of theBSTIteratorclass. Therootof the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.boolean hasNext()Returnstrueif there exists a number in the traversal to the right of the pointer, otherwise returnsfalse.int next()Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Examples
Example 1: Input ["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] Output [null, 3, 7, true, 9, true, 15, true, 20, false] Explanation BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False
Python Solution
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.stack = []
self._leftmost_inorder(root)
def _leftmost_inorder(self, root):
while root:
self.stack.append(root)
root = root.left
def next(self) -> int:
topmost_node = self.stack.pop()
if topmost_node.right:
self._leftmost_inorder(topmost_node.right)
return topmost_node.val
def hasNext(self) -> bool:
return len(self.stack) > 0
Java Solution
class BSTIterator {
private Stack stack;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
leftmostInorder(root);
}
private void leftmostInorder(TreeNode root) {
while (root != null) {
stack.push(root);
root = root.left;
}
}
public int next() {
TreeNode topmostNode = stack.pop();
if (topmostNode.right != null) {
leftmostInorder(topmostNode.right);
}
return topmostNode.val;
}
public boolean hasNext() {
return !stack.isEmpty();
}
}
C++ Solution
class BSTIterator {
private:
stack stack;
void leftmostInorder(TreeNode* root) {
while (root) {
stack.push(root);
root = root->left;
}
}
public:
BSTIterator(TreeNode* root) {
leftmostInorder(root);
}
int next() {
TreeNode* topmostNode = stack.top();
stack.pop();
if (topmostNode->right) {
leftmostInorder(topmostNode->right);
}
return topmostNode->val;
}
bool hasNext() {
return !stack.empty();
}
};
JavaScript Solution
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
class BSTIterator {
constructor(root) {
this.stack = [];
this.leftmostInorder(root);
}
leftmostInorder(root) {
while (root) {
this.stack.push(root);
root = root.left;
}
}
next() {
const topmostNode = this.stack.pop();
if (topmostNode.right) {
this.leftmostInorder(topmostNode.right);
}
return topmostNode.val;
}
hasNext() {
return this.stack.length > 0;
}
}
C# Solution
public class BSTIterator {
private Stack stack;
public BSTIterator(TreeNode root) {
stack = new Stack();
LeftmostInorder(root);
}
private void LeftmostInorder(TreeNode root) {
while (root != null) {
stack.Push(root);
root = root.left;
}
}
public int Next() {
TreeNode topmostNode = stack.Pop();
if (topmostNode.right != null) {
LeftmostInorder(topmostNode.right);
}
return topmostNode.val;
}
public bool HasNext() {
return stack.Count > 0;
}
}
Complexity Analysis
- Time Complexity:
- Constructor: O(h) where h is the height of the tree
- next(): O(1) amortized
- hasNext(): O(1)
- Space Complexity: O(h) where h is the height of the tree
Solution Explanation
This solution implements controlled inorder traversal:
- Key concept:
- Stack-based traversal
- Inorder traversal
- Lazy evaluation
- Algorithm steps:
- Initialize stack
- Process left path
- Handle right subtrees
- Maintain state
Key points:
- Constant average time
- Space efficient
- Iterator pattern
- BST properties