Created
November 13, 2017 16:01
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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