-
思路一
- 先中序遍历把所有结点放入队列,然后在调用next函数时pop队头即可
class BSTIterator { Queue<TreeNode> queue; public BSTIterator(TreeNode root) { queue = new LinkedList<>(); dfs(root); } private void dfs(TreeNode root){ if(null == root) return ; dfs(root.left); queue.offer(root); dfs(root.right); } public int next() { return queue.poll().val; } public boolean hasNext() { return !queue.isEmpty(); } }
- 时间复杂度:构造函数中因为要遍历是O(n),其余函数都是O(1)
- 空间复杂度:需要用队列保存所有结点信息,所以为O(n)
-
思路二(思路一的改进)
- 对思路一的空间复杂度可以有所改进,观察我们此前写过的遍历的非递归算法,可以发现外部while中每一次进行都是遍历了一次结点,所以next函数对应外部循环体中的内容,而hasNext函数则对应外部while循环的判断
class BSTIterator { TreeNode cur; Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<>(); cur = root; } public int next() { while(null != cur){ stack.push(cur); cur = cur.left; } cur = stack.pop(); int val = cur.val; cur = cur.right; return val; } public boolean hasNext() { return null != cur || !stack.isEmpty(); } }
- 时间复杂度:next函数中为O(h),其余都是O(1)
- 空间复杂度:栈中需要保存遍历过程的信息,最大需要保存 O(h)
剑指offer 专项突破版 55、二叉搜索树迭代器
最新推荐文章于 2022-12-21 14:04:19 发布