文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack<TreeNode*> index;
public:
BSTIterator(TreeNode *root) {
traverseLeft(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !index.empty();
}
/** @return the next smallest number */
int next() {
TreeNode* current = index.top();
index.pop();
traverseLeft(current->right);
return current->val;
}
void traverseLeft(TreeNode* root) {
TreeNode* current = root;
while(current) {
index.push(current);
current = current->left;
}
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/