Skip to content

Instantly share code, notes, and snippets.

@Siyu-Lei
Created June 30, 2018 00:46
Show Gist options
  • Save Siyu-Lei/fc315f3090861bfd6d8cb4267e793d87 to your computer and use it in GitHub Desktop.
Save Siyu-Lei/fc315f3090861bfd6d8cb4267e793d87 to your computer and use it in GitHub Desktop.
public class BSTIterator {
private Stack<TreeNode> stack;
private TreeNode cur;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
cur = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty() || cur != null;
}
/** @return the next smallest number */
public int next() {
while (cur != null) { // if cur == null means all left subtree node is traversed!
stack.push(cur);
cur = cur.left;
}
TreeNode node = stack.pop();
cur = node.right;
return node.val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment