力扣面试 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;
		}
	}
}
相关推荐
黄敬峰8 小时前
一文搞懂 Text2SQL:用大模型让自然语言直接查数据库
面试
政企项目老覃9 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水9 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR9 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵9 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽10 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil20810 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民11 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表