#173
Medium Algorithms Binary search tree iterator
Stack Tree Design Binary Search Tree Binary Tree Iterator
76.2% acceptance
Feb 27, 2026
9190
587
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 the BSTIterator class. The root of 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() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
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.
Solution
Rust
Time O(n)
Space O(n)
struct BSTIterator {
stack: Vec<Rc<RefCell<TreeNode>>>,
}
use std::rc::Rc;
use std::cell::RefCell;
impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
let mut stack = Vec::new();
let mut node = root;
while let Some(n) = node {
stack.push(Rc::clone(&n));
let left = n.borrow_mut().left.take();
node = left;
}
BSTIterator { stack }
}
fn next(&mut self) -> i32 {
if let Some(node_rc) = self.stack.pop() {
let mut node = node_rc.borrow_mut();
let val = node.val;
if let Some(right) = node.right.take() {
let mut current = Some(right);
while let Some(n) = current {
self.stack.push(Rc::clone(&n));
let left = n.borrow_mut().left.take();
current = left;
}
}
val
} else {
-1
}
}
fn has_next(&self) -> bool {
!self.stack.is_empty()
}
}