力扣面试 150二叉搜索树迭代器 中序遍历 栈模拟递归 步骤拆分

Problem: 173. 二叉搜索树迭代器

思路

👩‍🏫 三叶

复杂度

时间复杂度: O ( 1 ) O(1) O(1)

空间复杂度: O ( h ) O(h) O(h)

Code

Java 复制代码
class BSTIterator {
Stack<TreeNode> d = new Stack<>();

	public BSTIterator(TreeNode root)
	{
		dfsLeft(root);
	}

	public int next()
	{
		TreeNode root = d.pop();
		int ans = root.val;
		root = root.right;
		dfsLeft(root);
		return ans;
	}

	public boolean hasNext()
	{
		return !d.isEmpty();
	}

	void dfsLeft(TreeNode root)
	{
		while (root != null)
		{
			d.push(root);
			root = root.left;
		}
	}
}
相关推荐
春弦_1 小时前
自用算法整理二
数据结构·算法·图论
hetao17338372 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
java_nnnn3 小时前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
SailingCoder3 小时前
【封闭结束1】端到端交付:Agent 一次请求如何走完全链路
前端·安全·ai·面试·agent·harness
Navigator_Z3 小时前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
Interview Aid1124 小时前
Uber Interview Process 完整指南:面试流程、OA 真题与 VO 备考
面试·职场和发展
卡卡~~4 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
企业数字化笔记4 小时前
AI视频增强后画质怎么验收?插值基线、伪细节与帧间闪烁的检查方法
人工智能·算法·音视频
学逆向的5 小时前
C 内存属性
c语言·开发语言·算法·网络安全