Binary Search Tree Iterator
public class BSTIterator {
private TreeNode next;
private Stack<TreeNode> s = new Stack<TreeNode>();
private void addToStack(){
while(next != null){
s.add(next);
next = next.left;
}
next = null;
}
public BSTIterator(TreeNode root) {
next = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(next != null){
addToStack();
}
return !s.isEmpty();
}
/** @return the next smallest number */
public int next() {
if(!hasNext()){
return -1;
}
next = s.pop();
int ret = next.val;
next = next.right;
return ret;
}
}Last updated