原题链接在这里:https://leetcode.com/problems/binary-search-tree-iterator/
AC Java:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> stk = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
while(root != null){
stk.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stk.empty(); //error
}
/** @return the next smallest number */
public int next() {
TreeNode tn = stk.pop();
int res = tn.val;
if(tn.right != null){
tn = tn.right;
while(tn != null){
stk.push(tn);
tn = tn.left;
}
}
return res;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/