Skip to content

Instantly share code, notes, and snippets.

@fever324
Created August 12, 2015 12:33
Show Gist options
  • Save fever324/a76b04a927c90c598290 to your computer and use it in GitHub Desktop.
Save fever324/a76b04a927c90c598290 to your computer and use it in GitHub Desktop.
BST Iterator
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> s;
public BSTIterator(TreeNode root) {
s = new Stack<>();
pushAllLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !s.empty();
}
/** @return the next smallest number */
public int next() {
TreeNode toReturn = s.pop();
if(toReturn.right != null) {
pushAllLeft(toReturn.right);
}
return toReturn.val;
}
private void pushAllLeft(TreeNode node){
while(node != null) {
s.push(node);
node = node.left;
}
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment