力扣面试 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;
		}
	}
}
相关推荐
Swift社区1 天前
LeetCode 465 最优账单平衡
算法·leetcode·职场和发展
聆风吟º1 天前
【数据结构手札】空间复杂度详解:概念 | 习题
java·数据结构·算法
weixin_445054721 天前
力扣热题51
c++·python·算法·leetcode
是一个Bug1 天前
50道核心JVM面试题
java·开发语言·面试
地平线开发者1 天前
linux 常见稳定性问题分析方法
算法·自动驾驶
s砚山s1 天前
代码随想录刷题——二叉树篇(九)
算法
地平线开发者1 天前
大模型常见量化方法简介
算法·自动驾驶
smj2302_796826521 天前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode
栗少1 天前
英语自学手册:系统化进阶指南基于《英语自学手册》的方法论与行动路径
人工智能·算法
Moment1 天前
如何在前端编辑器中实现像 Ctrl + Z 一样的撤销和重做
前端·javascript·面试