```
/
* 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 {
public:
vector[HTML_REMOVED] s;
BSTIterator(TreeNode root) {
while(root){
s.emplace_back(root);
root = root->left;
}
}
int next() {
TreeNode* t = s.back();//最后一个即最左节点
s.pop_back(); //删掉末尾元素
int val = t->val;
t = t->right; //比他大的最小值,右子树的第一个左子树的最左边
while(t){
s.push_back(t); //
t = t->left;
}
return val;
}
bool hasNext() {
return !s.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();
/
```