public class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
pushThePath(stack, root);
}
public void pushThePath(Stack st, TreeNode root){
while(root != null){
st.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode cur = stack.pop();
pushThePath(stack, cur.right);
return cur.val;
}
}
网友评论