public class BSTIterator {
Stack stack = new Stack();
public BSTIterator(TreeNode root) {
TreeNode temp = root;
while(temp != null) {
stack.push(temp);
temp = temp.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode n = stack.pop();
TreeNode r = n.right;
while(r != null) {
stack.push(r);
r = r.left;
}
return n.val;
}
stack的最顶部就是整个BST的最小值(最左侧的叶子节点),每次pop一个值,都要把该root的right加进去,要熟悉BST的性质,左侧的都比右侧的小
详见230题
/**
public class BSTIterator { Stack stack = new Stack();
public BSTIterator(TreeNode root) {
TreeNode temp = root;
while(temp != null) {
stack.push(temp);
temp = temp.left;
}
}
}
/**