173. 二叉搜索树迭代器(中序遍历的递归法与迭代法)
实现一个二叉搜索树迭代器类BSTIterator ,表示一个按中序遍历二叉搜索树(BST)的迭代器:
BSTIterator(TreeNode root) 初始化 BSTIterator 类的一个对象。BST 的根节点 root 会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。
boolean hasNext() 如果向指针右侧遍历存在数字,则返回 true ;否则返回 false 。
int next()将指针向右移动,然后返回指针处的数字。
注意,指针初始化为一个不存在于 BST 中的数字,所以对 next() 的首次调用将返回 BST 中的最小元素。
你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 的中序遍历中至少存在一个下一个数字。
递归法
class BSTIterator {
private List<Integer> res;
private int index = 0;
public BSTIterator(TreeNode root) {
res = new ArrayList<>();
inOrder(root);
}
public void inOrder(TreeNode root)
{
//中序递归的常规做法
if(root == null) return ;
inOrder(root.left);
res.add(root.val);
inOrder(root.right);
}
public int next() {
return res.get(index++);
}
public boolean hasNext() {
if((index) == res.size()) return false;
return true;
}
}
非递归迭代法
首先有迭代法的模板
//二叉树的先根遍历
void preOrder(BTNode* root) {
stack<BTNode*> st;
while (root or not st.empty()) {
while (root) {
cout << root->val << " ";
st.push(root);
root = root->left;
}
root = st.top();
st.pop();
root = root->right;
}
}
//二叉树的中根遍历
//注意中根遍历和先根遍历代码的差别仅仅在于ans.push_back(root->val);的位置
void inOrder(BTNode* root) {
stack<BTNode*> st;
while (root or not st.empty()) {
while (root) { //步骤1
st.push(root);
root = root->left;
}
root = st.top(); //步骤2
st.pop();
cout << root->val << " ";
root = root->right; //步骤3
}
}
//二叉树的后根遍历
//注意后根遍历和先根遍历代码的差别在于先将右子树入栈,再将左子树入栈,最后进行一次翻转
void postOrder(BTNode* root) {
vector<gg> ans;
stack<BTNode*> st;
while (root or not st.empty()) {
while (root) {
ans.push_back(root->val);
st.push(root);
root = root->right;
}
root = st.top();
st.pop();
root = root->left;
}
reverse(begin(ans), end(ans));
for(gg i: ans){
cout << i << " ";
}
}
从中可以看出迭代法是按3步走的,1.遍历左子树 2.根 3.遍历右子树
那么本题有两种做法,
1.直接迭代出答案然后在next的函数遍历
2.利用一个队列在next的函数中处理树
class BSTIterator {
Deque<TreeNode> d = new ArrayDeque<>();
public BSTIterator(TreeNode root) {
// 步骤 1
dfsLeft(root);
}
public int next() {
// 步骤 2
TreeNode root = d.pollLast();
int ans = root.val;
// 步骤 3
root = root.right;
// 步骤 1
dfsLeft(root);
return ans;
}
void dfsLeft(TreeNode root) {
while (root != null) {
d.addLast(root);
root = root.left;
}
}
public boolean hasNext() {
return !d.isEmpty();
}
}