struct TreeNode {
val: i32,
left: Option<Box<TreeNode>>,
right: Option<Box<TreeNode>>,
}
// BST structure:
// 7
// / \
// 3 15
// / \
// 9 20
// Iterator initialized with root node 7The BST Iterator returns nodes in ascending order. The in-order traversal of the tree is 3, 7, 9, 15, 20. Calling next() four times returns the first four values in this order.
The stack stores nodes from the root to the current node. In the worst case, if the BST is skewed (like a linked list), the stack can hold all n nodes, so space complexity is O(n).
fn next(&mut self) -> i32 {
let node = self.stack.pop().unwrap();
let mut current = node.right;
while let Some(n) = current {
self.stack.push(n.clone());
current = n.left;
}
node.val
}If the stack is empty, calling pop() returns None. Using unwrap() on None causes a panic at runtime.
fn new(root: Option<Box<TreeNode>>) -> Self {
let mut stack = Vec::new();
let mut current = root;
// Fill stack with left children
while let Some(node) = current {
// ???
}
BSTIterator { stack }
}In Rust, clone the node to push onto the stack since the loop consumes ownership of the node when moving to its left child (current = node.left.clone()).
The BST Iterator returns each node exactly once. For 10 nodes, next() can be called 10 times before no nodes remain.
