/**
* 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;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
if(root != null)
pushleft(root);
}
private void pushleft(TreeNode root) {
while(root != null) {
stack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode temp = stack.pop();
if(temp.right != null)
pushleft(temp.right);
return temp.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
2015年1月4日星期日
[Leetcode] Binary Search Tree Iterator
The solution is also available here:https://gist.github.com/pyemma/bbe39014f436f2a5aa5b
订阅:
博文评论 (Atom)
没有评论:
发表评论