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();
 */
相关推荐
BothSavage4 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn4 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽5 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说21 小时前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术1 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六1 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术1 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize1 天前
初识DFS 与 BFS:递归、队列与图遍历
算法