力扣面试 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 小时前
2027 年最火的 AI 项目出炉,No.1 易主!
面试·架构·github
Eyfcom1 小时前
〖物流数据安全 02〗差分隐私与同态加密的工程边界:跨境物流快递系统该为隐私付出多少计算代价?
算法·机器学习·同态加密·跨境物流快递系统·物流数据安全
郝学胜-神的一滴2 小时前
Effective STL 条款15:注意字符串实现上的差异
java·开发语言·数据结构·c++·算法·visualstudio
wuyk5553 小时前
AI 时代的嵌入式该怎么学-09-嵌入式vs后端vs算法
人工智能·stm32·单片机·嵌入式硬件·mcu·物联网·算法
圆心角3 小时前
Agent 上下文原理:为什么“记住”比“推理”更难
前端·面试·agent
labuladong4 小时前
全新的算法 & Agent 课程页上线
算法·llm·agent
leobertlan6 小时前
好玩系列 | 以简构繁,从把玩一把天平进入信息论和编码
算法
电科_银尘6 小时前
【大模型算法与工程 48】项目实战:可调用、可追踪的大模型问答服务
算法