Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created August 23, 2019 17:06
Show Gist options
  • Save shixiaoyu/18d5cb2b7e72bfaa12d9afc24aed333f to your computer and use it in GitHub Desktop.
Save shixiaoyu/18d5cb2b7e72bfaa12d9afc24aed333f to your computer and use it in GitHub Desktop.
public class BinarySearchTreeIterator {
private Stack<TreeNode> stack = null;
public BinarySearchTreeIterator(TreeNode root) {
this.stack = new Stack<TreeNode>();
while (root != null) {
this.stack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !this.stack.isEmpty();
}
/** @return the next smallest number */
// essentially using a stack to implement in-order traversal
public int next() {
// caller should check using hasNext() else NoSuchElementException
TreeNode t = this.stack.pop();
if (t.right != null) {
this.stack.push(t.right);
TreeNode c = t.right.left;
while (c != null) {
this.stack.push(c);
c = c.left;
}
}
return t.val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment