LeetCode 173. Binary Search Tree Iterator
原题链接在这里:https://leetcode.com/problems/binary-search-tree-iterator/
题目:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the BST.
Note: next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
题解:
用一个stack把所有最左边的node压进 stack中。
判断hasNext()时就是看stack 是否为空.
next()返回stack顶部top元素,若是top有右子树,就把右子树的所有最左node压入stack中.
constructor time complexity: O(h).
hashNext time complexity: O(1).
next time complexity: O(h).
Space: O(h), stack 最大为树的高度。
AC Java:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 11 public class BSTIterator { 12 Stack<TreeNode> stk; 13 14 public BSTIterator(TreeNode root) { 15 stk = new Stack<TreeNode>(); 16 while(root != null){ 17 stk.push(root); 18 root = root.left; 19 } 20 } 21 22 /** @return whether we have a next smallest number */ 23 public boolean hasNext() { 24 return !stk.isEmpty(); 25 } 26 27 /** @return the next smallest number */ 28 public int next() { 29 TreeNode top = stk.pop(); 30 TreeNode rightLeft = top.right; 31 while(rightLeft != null){ 32 stk.push(rightLeft); 33 rightLeft = rightLeft.left; 34 } 35 36 return top.val; 37 } 38 } 39 40 /** 41 * Your BSTIterator will be called like this: 42 * BSTIterator i = new BSTIterator(root); 43 * while (i.hasNext()) v[f()] = i.next(); 44 */
类似All Elements in Two Binary Search Trees, Binary Tree Inorder Traversal, Inorder Successor in BST.
【推荐】FlashTable:表单开发界的极速跑车,让你的开发效率一路狂飙
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 领域模型应用
· 记一次 ADL 导致的 C++ 代码编译错误
· MySQL查询执行顺序:一张图看懂SQL是如何工作的
· 为什么PostgreSQL不自动缓存执行计划?
· 于是转身独立开发者
· Cursor 1.2重磅更新,这个痛点终于被解决了!
· C#/.NET/.NET Core优秀项目和框架2025年6月简报
· C#开发的Panel滚动分页控件(滑动版) - 开源研究系列文章
· 从被喷“假开源”到登顶 GitHub 热榜,这个开源项目上演王者归来!
· 上周热点回顾(6.30-7.6)