解题思路:
(1)中序遍历
/**
* 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:
vector<int> v;
int count=0,temp;
public:
void helper(TreeNode* root) {
if(!root) return;
helper(root->left);
v.push_back(root->val);
helper(root->right);
}
BSTIterator(TreeNode* root) {
helper(root);
}
int next() {
if(count<v.size()) {
temp=v[count];
count++;
return temp;
}
else return -1;
}
bool hasNext() {
if(count<v.size()) return true;
else return false;
}
};
/**
* 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();
*/