leetcode 173.二叉搜索树迭代器

1.题目要求:

2.题目代码:

csharp 复制代码
/**
 * 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();
 */
相关推荐
宝贝儿好4 小时前
【强化学习实战】第十一章:Gymnasium库的介绍和使用(1)、出租车游戏代码详解(Sarsa & Q learning)
人工智能·python·深度学习·算法·游戏·机器学习
pao__pao_7 小时前
计算机系统大作业 程序人生-Hello’s P2P
程序人生·职场和发展·课程设计
munubak7 小时前
程序人生-Hello’s P2P
程序人生·职场和发展
努力学算法的蒟蒻7 小时前
day109(3.10)——leetcode面试经典150
面试·职场和发展
芝士爱知识a7 小时前
【程序人生】码农考公指南:是“降维打击”还是“围城自困”?
程序人生·职场和发展·程序员·公务员·考公·职场规划
炒鸡菜6667 小时前
程序人生-Hello’s P2P
c语言·程序人生·职场和发展
weixin_458872617 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll7 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人7 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn8 小时前
模拟题刷题3
java·数据结构·算法