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();
 */
相关推荐
文丑颜不良啊12 分钟前
LeetCode3421~3440题目解析
java·leetcode
cjz38992 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子135 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘16 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴19 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David19 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
LK_071 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
文丑颜不良啊1 天前
LeetCode3341~3360题目解析
java·leetcode