在调用next()的时候,返回下次个最小的值。调用hasNext() 要返回还有没有这样的数。
时间复杂度要保证在O(1), 空间复杂度要在O(h), h是树的高度。
一个很直观的想法就是,要获得二分搜索的从小到大的序列,只要对树进行中序遍历就可得。
中序遍历后,就得到从小到大的序列了,每次调用next,就返回index++下的值。
这里有的一个限制就是空间复杂度,前面讲的解法的空间复杂度在O(n)。
所以,在这里要做的一个就是讲中序遍历拆解开。
当你需要的时候,再进行相应的后续遍历,返回当前的最小结果。
这样可以节约时间,不需要数组储存所有的遍历结果了。
代码:
public class BSTIterator {
Stack<TreeNode> store;
public BSTIterator(TreeNode root) {
store = new Stack<>();
while (root != null) {
store.push(root);
root = root.left;
}
}
/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
return !store.empty();
}
/**
* @return the next smallest number
*/
public int next() {
TreeNode cur = store.pop();
int value = cur.val;
if (cur.right != null) {
cur = cur.right;// let cur.right be the current node
store.push(cur);
cur = cur.left;
while (cur != null) {
store.push(cur);
cur = cur.left;
}
}
return value;
}
}