Last active
August 5, 2017 01:17
-
-
Save cixuuz/293eb5ee68d65c68c09048e672d6200b to your computer and use it in GitHub Desktop.
[173 Binary Search Tree Iterator] #leetcode
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 { | |
private Stack<TreeNode> stack = new Stack<TreeNode>(); | |
public BSTIterator(TreeNode root) { | |
pushLeft(root); | |
} | |
/** @return whether we have a next smallest number */ | |
public boolean hasNext() { | |
return !stack.isEmpty(); | |
} | |
/** @return the next smallest number */ | |
public int next() { | |
TreeNode next_node = stack.pop(); | |
pushLeft(next_node.right); | |
return next_node.val; | |
} | |
private void pushLeft(TreeNode node) { | |
while (node != null) { | |
stack.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