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();
 */
相关推荐
货拉拉技术1 小时前
视觉底座:货拉拉OCR的进阶之路
算法
__underline__1 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法
风落青芜4 小时前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
Pniubi8 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊18 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考19 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊20 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~1 天前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯1 天前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好1 天前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频