这道题的关键在于在建立迭代器的时候,将二叉树遍历一遍,按照从大到小的顺序压入栈中,具体代码如下
public class BSTIterator {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Stack<Integer> data = new Stack<Integer>();
public BSTIterator(TreeNode root) {
helpFunction(root);
}
private void helpFunction(TreeNode root){
if(root == null){
return;
}
if(root.right != null){
helpFunction(root.right);
}
data.push(root.val);
if(root.left != null){
helpFunction(root.left);
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return data.size() != 0;
}
/** @return the next smallest number */
public int next() {
return data.pop();
}
}