遇难心不慌,遇易心更细。
题目
实现一个二叉搜索树迭代器类BSTIterator
,表示一个按中序遍历二叉搜索树(BST)的迭代器:
-
BSTIterator(TreeNode root)
初始化BSTIterator
类的一个对象。BST 的根节点root
会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。 -
boolean hasNext()
如果向指针右侧遍历存在数字,则返回true
;否则返回false
。 -
int next()
将指针向右移动,然后返回指针处的数字。
注意,指针初始化为一个不存在于 BST 中的数字,所以对 next()
的首次调用将返回 BST 中的最小元素。
你可以假设 next()
调用总是有效的,也就是说,当调用 next()
时,BST 的中序遍历中至少存在一个下一个数字。
![](https://img.haomeiwen.com/i7172850/99e70f6b5b075757.png)
输入
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
输出
[null, 3, 7, true, 9, true, 15, true, 20, false]
解释
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // 返回 3
bSTIterator.next(); // 返回 7
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 9
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 15
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 20
bSTIterator.hasNext(); // 返回 False
进阶:设计一个满足下述条件的解决方案:next()
和 hasNext()
操作均摊时间复杂度为 O(1)
,并使用 O(h)
内存。其中 h
是树的高度。
解题思路
-
递归+队列:中序遍历使用递归比较简单直接,存到队列里面达到
O(1)
的时间复杂度。 -
迭代:进阶设计,满足空间复杂度
O(h)
,本质是模拟展开递归。
递归+队列
class BSTIterator {
TreeNode root;
List<TreeNode> list = new ArrayList<>();
int index = 0;
public BSTIterator(TreeNode root) {
this.root = root;
dfs(root);
}
void dfs(TreeNode node) {
if(node == null) return;
dfs(node.left);
list.add(node);
dfs(node.right);
}
public int next() {
return list.get(index++).val;
}
public boolean hasNext() {
return index < list.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)
,n
为树的节点数,递归会访问每个节点一次,next
和hasNext
为O(1)
。 - 空间复杂度:
O(n)
,递归栈空间n
,队列空间n
。
迭代
class BSTIterator {
TreeNode root;
Deque<TreeNode> stk = new LinkedList<TreeNode>();
public BSTIterator(TreeNode root) {
this.root = root;
}
public int next() {
while (root != null) {
stk.push(root);
root = root.left;
}
root = stk.pop();
int value = root.val;
root = root.right;
return value;
}
public boolean hasNext() {
return root != null || !stk.isEmpty();
}
}
复杂度分析
- 时间复杂度:
O(n)
,n
为树节点数,由于总共会遍历一次树的所有节点,所以next
均摊时间复杂度为O(1)
。 - 空间复杂度:
O(h)
,h
为树的高度,栈空间最大为树高度,最坏情况下h == n
。
网友评论