1.题目要求:
2.题目代码:
/*** 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 {
public://设置vector容器,输入树结点的值vector<int> tree_val;//设置迭代的下标int i;void inorder_travel(TreeNode* root){if(root == NULL){return;}inorder_travel(root->left);tree_val.push_back(root->val);inorder_travel(root->right);}BSTIterator(TreeNode* root) {//采用中序遍历存入节点值inorder_travel(root);i = -1;}int next() {//迭代一次,返回值this->i++;return tree_val[i];}bool hasNext() {//判断数组是否超限if(i + 1 >= tree_val.size()){return false;}else{return true;}}
};/*** 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();*/