迭代器是程序设计的软件设计模式,可在容器对象(如链表或数组)上遍访的接口,设计人员无需关心对象的内存分配的实现细节。
思路:
这一题实际上只要能够实现next和hasNext函数的功能即可。这里所谓的迭代器是对节点的值(node->val)进行访问。
所以我们第一种方法,可以用用递归将中序遍历的值存入数组中,然后用下标来判断当前节点是否有下一个节点,并且下一个节点的值为多少。
/**
* 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 {
vector<int> vec;
int index;
void inorder(TreeNode* root){
if(!root) return;
inorder(root->left);
vec.push_back(root->val);
inorder(root->right);
}
public:
BSTIterator(TreeNode* root):index(0) {
inorder(root);
}
int next() {
return vec[index++];
}
bool hasNext() {
return index<vec.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();
*/
既然上面用了递归的方法,那么第二种方法自然是迭代的方法,用迭代的方式来中序遍历。
并且我们不需要计算出中序遍历的全部结果,只需要实时维护当前栈的情况就可以了。
/**
* 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 {
TreeNode*curr;
stack<TreeNode*> stk;
public:
BSTIterator(TreeNode* root) {
curr=root;
}
int next() {
while(curr){
stk.push(curr);
curr=curr->left;
}
curr=stk.top();
stk.pop();
int res=curr->val;
curr=curr->right;
return res;
}
bool hasNext() {
return curr||!stk.empty();
}
};
/**
* 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();
*/