/**
* 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<int> V;
int ind = 0;
void inOrder(TreeNode* root) {
if(!root) return ;
inOrder(root->left);
V.push_back(root->val);
inOrder(root->right);
}
BSTIterator(TreeNode* root) {
inOrder(root);
}
int next() {
return V[ind++];
}
bool hasNext() {
return ind < V.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 {
public:
stack<TreeNode*> S;
TreeNode* p;
BSTIterator(TreeNode* root) {
for(p = root; p; p = p->left) S.push(p);
}
int next() {
while(!S.empty()
&& (S.top()->val == -1 && !S.top()->right || S.top()->right && S.top()->right->val == -1)) S.pop();
while(!S.empty() && S.top()->left && S.top()->left->val != -1) S.push(S.top()->left);
int temp = S.top()->val;
S.top()->val = -1;
if(S.top()->right) S.push(S.top()->right);
return temp;
}
bool hasNext() {
while(!S.empty()
&& (S.top()->val == -1 && !S.top()->right || S.top()->right && S.top()->right->val == -1)) S.pop();
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();
*/