Created
August 12, 2015 12:33
-
-
Save fever324/a76b04a927c90c598290 to your computer and use it in GitHub Desktop.
BST Iterator
This file contains 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
/** | |
* 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