Skip to content

Instantly share code, notes, and snippets.

@xynophon
Created July 11, 2015 06:32
Show Gist options
  • Select an option

  • Save xynophon/3f4226698eddcc686105 to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/3f4226698eddcc686105 to your computer and use it in GitHub Desktop.
LeetCode Binary Search Tree Iterator
import java.util.*;
public class BSTIterator {
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
Stack<Integer> nums = new Stack<>();
public BSTIterator(TreeNode root) {
Stack<TreeNode> nodes = new Stack<>();
TreeNode p = root;
while(!nodes.isEmpty() || p != null){
if(p != null){
nodes.push(p);
p = p.right;
}else{
TreeNode n = nodes.pop();
nums.push(n.val);
p = n.left;
}
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(nums.size() > 0){
return true;
}else{
return false;
}
}
/** @return the next smallest number */
public int next() {
return nums.pop();
}
/**
* 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