题目链接:https://leetcode.com/problems/binary-search-tree-iterator/
要求构造一个二叉搜索树的迭代器,复杂度要求为:next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
思路一:
最朴素的思路就是维护一个先序遍历数组和一个数组索引,代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BSTIterator {
public ArrayList<Integer> inorderArray;
public int index;
public BSTIterator(TreeNode root) {
inorderArray=new ArrayList();
index=0;
inorderTraverse(root);
}
private void inorderTraverse(TreeNode node)
{
if(node==null)
return;
inorderTraverse(node.left);
inorderArray.add(node.val);
inorderTraverse(node.right);
}
/** @return the next smallest number */
public int next() {
return inorderArray.get(this.index++);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return this.index<this.inorderArray.size();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
这个运行效率主要花费在先序遍历上了,效率偏低。整体空间复杂度为O(n),迭代器构造的时间复杂度和空间复杂度均为O(n),next() and hasNext() 的时间复杂度为O(1),但是空间复杂度为O(n),侥幸AC。
思路二:动态地维护一个栈,当要找下一个最小数时,就弹栈,这样就能动态实时分步地进行先序遍历了:
class BSTIterator {
public Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack=new Stack<>();
TreeNode p=root;
while(p!=null){
stack.push(p);
p=p.left;
}
}
/** @return the next smallest number */
public int next() {
TreeNode tmp=stack.pop();
int ans=tmp.val;
tmp=tmp.right;
while(tmp!=null){
stack.push(tmp);
tmp=tmp.left;
}
return ans;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
}
这个online算法的空间的复杂度为O(h),而时间复杂度为O(1)。
本文探讨了二叉搜索树迭代器的两种实现方法。第一种使用先序遍历数组,虽然next()和hasNext()操作时间复杂度为O(1),但空间复杂度为O(n)。第二种采用动态维护栈的方式,每次寻找最小数时弹栈,实现在线算法,空间复杂度降低到O(h),时间复杂度仍保持O(1)。
3619

被折叠的 条评论
为什么被折叠?



