Binary Search Tree Iterator
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
TreeNode* curt ;
stack<TreeNode*> sdk;
BSTIterator(TreeNode *root) {
curt = root;
//init
while(curt != NULL){
sdk.push(curt);
curt = curt->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !sdk.empty();
}
/** @return the next smallest number */
int next() {
//pop
TreeNode * node = sdk.top();
sdk.pop();
curt = node->right;
//push all left child to stack
//(this code snippet can not move to other position , you gotta push stack immediately after pop stack
// otherwise the hasnext() will return false )
while(curt != NULL){
sdk.push(curt);
curt = curt->left;
}
return node->val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/