Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 13, 2017 16:01
Show Gist options
  • Save shailrshah/48588e4586aee1006f92b3ec3521333d to your computer and use it in GitHub Desktop.
Save shailrshah/48588e4586aee1006f92b3ec3521333d to your computer and use it in GitHub Desktop.
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
public class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
pushLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
if(!hasNext())
throw new java.util.EmptyStackException();
TreeNode root = stack.pop();
pushLeft(root.right);
return root.val;
}
private void pushLeft(TreeNode root) {
while(root!=null) {
stack.push(root);
root = root.left;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment