问题
例子
思路
-
方法1
使用队列保存递增数组,为什么用队列?因为方便,直接poll即可,但缺点是空间复杂度是O(n)而不是O(logn)
-
方法2
使用栈,初始保存所有的左子树。
获取next时,取栈顶元素的值,并把下一个最小的大于该值的结点放入栈
next方法:看起来是O(n),其实是O(1),因为其中的循环加上初始化的循环,共放入栈中n个元素,总共会有O(n)次操作,均摊到每一次next()的话平均时间复杂度则是O(n)/n=O(1)
代码
//方法1
class BSTIterator {
Queue<Integer> q = new LinkedList<>();
public BSTIterator(TreeNode root) {
midOrder(root);
}
public int next() {
//因为题目中假设调用next时总是有元素的
return q.poll();
}
public boolean hasNext() {
return q.size()>0;
}
public void midOrder(TreeNode root) {
if(root==null) return;
if(root.left!=null) midOrder(root.left);
q.offer(root.val);
if(root.right!=null) midOrder(root.right);
}
}
//方法2
class BSTIterator {
Stack<TreeNode> s = new Stack<>();
public BSTIterator(TreeNode root) {
while(root!=null) {
s.push(root);
root = root.left;
}
}
public int next() {
//因为题目中假设调用next时总是有元素的
//返回值,并把下一个结点放入栈
TreeNode node = s.pop();
TreeNode right = node.right;
while(right!=null) {
s.push(right);
right=right.left;
}
return node.val;
}
public boolean hasNext() {
return s.size()>0;
}
}