用stack来存储node,先存储最左边的node,再往右移动
public class BSTIterator {
Stack<TreeNode> stack = new Stack();
public BSTIterator(TreeNode root) {
pushLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode curr = stack.pop();
pushLeft(curr.right);
return curr.val;
}
/** push all left node for a node */
private void pushLeft(TreeNode node) {
for (; node != null;) {
stack.push(node);
node = node.left;
}
}
}