题目介绍
力扣173题:leetcode-cn.com/problems/bi…
分析
我们可以直接对二叉搜索树做一次完全的递归遍历,获取中序遍历的全部结果并保存在数组中。随后,我们利用得到的数组本身来实现迭代器。
代码如下:
class BSTIterator {
private int idx;
private List<Integer> arr;
public BSTIterator(TreeNode root) {
idx = 0;
arr = new ArrayList<Integer>();
inorderTraversal(root, arr);
}
public int next() {
return arr.get(idx++);
}
public boolean hasNext() {
return idx < arr.size();
}
private void inorderTraversal(TreeNode root, List<Integer> arr) {
if (root == null) {
return;
}
inorderTraversal(root.left, arr);
arr.add(root.val);
inorderTraversal(root.right, arr);
}
}
复杂度分析
-
时间复杂度:初始化需要 O(n)的时间,其中 n 为树中节点的数量。随后每次调用只需要 O(1) 的时间。
-
空间复杂度:O(n),因为需要保存中序遍历的全部结果。