/**
* 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 *> stk;
void keep_pushing_left(TreeNode *&root){
while(root){
stk.push(root);
root = root -> left;
}
}
public:
BSTIterator(TreeNode *root) {
keep_pushing_left(root);
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !stk.empty();
}
/** @return the next smallest number */
int next() {
TreeNode *top = stk.top();
int val = top -> val;
stk.pop();
if(top->right){
keep_pushing_left(top = top->right);
}
return val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
Leetcode Binary Search Tree Iterator
最新推荐文章于 2022-06-10 17:57:38 发布