Complete the code to initialize the stack in the BST iterator constructor.
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
let mut stack = Vec::new();
let mut current = root;
while let Some(node) = current {
stack.push(node.clone());
current = node.borrow().[1];
}
BSTIterator { stack }
}The iterator pushes all left children to the stack initially to start with the smallest element.
Complete the code to check if the iterator has a next element.
fn has_next(&self) -> bool {
!self.stack.[1]()
}has_next returns true if the stack is not empty, so we check if it is empty and negate the result.
Fix the error in the next() method to correctly push left children of the right subtree.
fn next(&mut self) -> i32 {
let node = self.stack.pop().unwrap();
let mut current = node.borrow().[1].clone();
while let Some(n) = current {
self.stack.push(n.clone());
current = n.borrow().[2];
}
node.borrow().val
}After popping the node, we move to its right child and push all left children of that subtree onto the stack.
Fill both blanks to complete the BSTIterator struct and implement the constructor.
struct BSTIterator {
stack: Vec<Rc<RefCell<TreeNode>>>,
}
impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
let mut stack = Vec::new();
let mut current = root;
while let Some(node) = current {
stack.push(node.clone());
current = node.borrow().[1];
}
BSTIterator { [2] }
}
}The stack stores nodes for iteration, and we initialize it by pushing left children. The struct field is named stack.
Fill all three blanks to complete the next() method of BSTIterator.
fn next(&mut self) -> i32 {
let node = self.stack.pop().unwrap();
let mut current = node.borrow().[1].clone();
while let Some(n) = current {
self.stack.push(n.clone());
current = n.borrow().[2];
}
node.borrow().[3]
}We start from the right child of the popped node, push all left children, and finally return the node's value.
