一、题目
二、思路
- 题目要求BST二叉搜索树的中序遍历迭代器,所以只需要对BST先进行中序遍历,得到这个中序遍历数组,然后对该数组进行
next
操作和havenext
操作即可。 - 在实现过程中,注意引用、构造函数的初始化列表等细节。
三、代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
private:
//得到中序遍历数组res
void inorder(TreeNode* root, vector<int>& res){
if(!root) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root){
vector<int>ans;
inorder(root, ans);
return ans;
}
vector<int>arr;
int idx;
public:
//初始化列表
BSTIterator(TreeNode* root): idx(0), arr(inorderTraversal(root)){}
int next() {
return arr[idx++];
}
bool hasNext() {
return (idx < arr.size());
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/