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();
 */
相关推荐
Nazarick1 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴1 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴2 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_113 小时前
算法札记:有限差分
算法
忙里偷闲学python3 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农3 小时前
11.21程序设计
数据结构·算法
Tisfy4 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6174 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
灯澜忆梦5 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
Shaoshing6 小时前
LeetCode100 155.最小栈
java·数据结构·算法