```
public class BSTIterator {
private BSTIterator runner; // the nested iterator.
private boolean rootYielded=false; // if root value has already been yielded.
private TreeNode root; // store the root node.
public BSTIterator(TreeNode root) {
if(root==null) return;
this.root=root;
runner= new BSTIterator(root.left);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(runner==null) return false;
if(runner.hasNext()) return true;
if(rootYielded) return false;
return true;
}
/** @return the next smallest number */
public int next() {
if(runner==null) return 0;
if(runner.hasNext()) return runner.next();
if(rootYielded) return 0;
runner = new BSTIterator(root.right);
rootYielded=true;
return root.val;
}
}
```

The recursion is easy to understand. It works by first iterating its left subtree, then yield itself, and then iterating its right subtree.