力扣面试 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 小时前
[非技术文章]过去八个月了,总想写点什么。
面试
人间乄惊鸿客6 小时前
c++ 右值
c++·算法
fanstuck7 小时前
AI 客服答错了,三分钟分清是 Prompt 还是系统的锅
算法
田里的水稻8 小时前
FA_编程算法200个分类列数-SUM
算法·分类·数据挖掘
ShineWinsu8 小时前
对于Qt:TCP的解析
linux·c++·qt·网络协议·面试·tcp·客户端
猿人谷10 小时前
从百万个 Pareto 解中选出 100 个:Riesz s-Energy 如何实现高效的多样性选择?
后端·算法·aigc
地平线开发者10 小时前
地平线 × 同济无人车队:PointPillars 从浮点模型到 BPU 部署
算法·自动驾驶
iiiiii1111 小时前
从最大熵到 SAC:Soft Q-Learning 与 Soft Actor-Critic 公式推导笔记
人工智能·笔记·算法·机器学习·强化学习