Java | Leetcode Java题解之第173题二叉搜索树迭代器

题目:

题解:

java 复制代码
class BSTIterator {
    private TreeNode cur;
    private Deque<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        cur = root;
        stack = new LinkedList<TreeNode>();
    }
    
    public int next() {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        int ret = cur.val;
        cur = cur.right;
        return ret;
    }
    
    public boolean hasNext() {
        return cur != null || !stack.isEmpty();
    }
}
相关推荐
计算机安禾19 分钟前
【C语言程序设计】第31篇:指针与函数
c语言·开发语言·数据结构·c++·算法·leetcode·visual studio
Frostnova丶23 分钟前
LeetCode 3070. 元素和小于等于 k 的子矩阵数目
算法·leetcode·矩阵
菜鸟小九1 小时前
hot100(71-80)
java·数据结构·算法
大傻^1 小时前
LangChain4j 1.4.0 快速入门:JDK 11+ 基线迁移与首个 AI Service 构建
java·开发语言·人工智能
代码探秘者1 小时前
【大模型应用】4.分块之六大策略
java·数据结构·后端·python·spring
码喽7号1 小时前
Springboot学习六:MybatisPlus的多表查询以及分页查询
java·spring boot·学习
不想看见4041 小时前
Implement Queue using Stacks栈和队列--力扣101算法题解笔记
笔记·算法·leetcode
那我掉的头发算什么1 小时前
【博客系统】基于Spring全家桶的博客系统(下)
java·后端·spring·mybatis·开发
不吃香菜学java1 小时前
苍穹外卖-新增菜品需求分析
java·spring boot·spring·tomcat·maven·ssm
MrZhangBaby1 小时前
SQL-leetcode—3482. 分析组织层级
数据库·sql·leetcode