LeetCode 173. 二叉搜索树迭代器
原题链接
中等
作者:
回归线
,
2021-03-28 21:19:59
,
所有人可见
,
阅读 261
/**
* 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 {
private:
stack<TreeNode*> stk;
public:
BSTIterator(TreeNode* root) {
while(root) {
stk.push(root);
root = root->left;
}
}
int next() {
auto t = stk.top();
stk.pop();
int res = t->val;
t = t->right;
while (t) {
stk.push(t);
t = t->left;
}
return res;
}
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();
*/