```
public class BSTIterator {
Stack<TreeNode> s;
public BSTIterator(TreeNode root) {
s = new Stack<TreeNode>();
while(root!=null)
{
s.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !s.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode result = s.pop();
TreeNode node = result.right;
while(node!=null)
{
s.push(node);
node = node.left;
}
return result.val;
}
}
```