LeetCode 173. 二叉搜索树迭代器
原题链接
中等
作者:
飞呀
,
2021-05-16 11:51:12
,
所有人可见
,
阅读 243
/**
* 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) {}
* };
*/
const int N = 100000;
class BSTIterator {
private:
vector<int> arr;
int index;
void inOrder(TreeNode* root){
if(root == nullptr){
return;
}
inOrder(root->left);
arr.push_back(root->val);
//printf("%d\n", root->val);
index++;
inOrder(root->right);
}
public:
BSTIterator(TreeNode* root) {
inOrder(root);
index = 0;
}
int next() {
return arr[index++];
}
bool hasNext() {
return index < arr.size();
}
};
/**
* 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();
*/