173. Binary Search Tree Iterator
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
pushNodes(root);
}
/** @return the next smallest number */
public int next() {
TreeNode root = stack.pop();
pushNodes(root.right);
return root.val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
private void pushNodes(TreeNode root) {
while(root != null) {
stack.push(root);
root = root.left;
}
}
}