173. 二叉搜索树迭代器
作者:
owonder
,
2020-08-13 11:05:48
,
所有人可见
,
阅读 680
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
stack<TreeNode*> stk;
BSTIterator(TreeNode* root) {
if(root){
stk.push(root);
if(root->left){
TreeNode*left=root->left;
while(left){
stk.push(left);
left=left->left;
}
}
}
}
/** @return the next smallest number */
int next() {
TreeNode*top=stk.top();
stk.pop();
if(top->right){
TreeNode*right=top->right;
stk.push(right);
if(right->left){
TreeNode*left=right->left;
while(left){
stk.push(left);
left=left->left;
}
}
}
return top->val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !stk.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();
*/