[Java]leetcode173 Binary Search Tree Iterator
来源:互联网 发布:小米路由器数据迁移 编辑:程序博客网 时间:2024/04/28 12:34
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.
题意:写一个二叉查找树的迭代器,实现hasNext()和next()的功能。next()每次返回二叉树中未访问的最小值。要求的平均时间复杂度是O(1)和空间复杂度是O(h)。
解题思路:next()每次返回二叉树中未访问的最小值。也就是将二叉树中序遍历,并将对应值输出。这里面注意的是空间和时间的复杂度。
public class BSTIterator {//将中序遍历的功能嵌查在整个程序中 TreeNode current; Stack<TreeNode> stack; public BSTIterator(TreeNode root) { current=root; stack=new Stack<TreeNode>(); while(current!=null)//因为只可能是左节点才是最小值,将所有左子树节点入栈,保证空间复杂度是O(h) { stack.push(current); current=current.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { current=stack.pop(); int res=current.val;//这一步已经得到最小值 current=current.right;//但要考虑到右子树的遍历 while(current!=null) { stack.push(current); current=current.left; } return res; }}
0 0
- [Java]leetcode173 Binary Search Tree Iterator
- LeetCode173:Binary Search Tree Iterator
- LeetCode173-Binary Search Tree Iterator
- LeetCode173 Binary Search Tree Iterator
- LeetCode173——Binary Search Tree Iterator
- LeetCode173—Binary Search Tree Iterator
- Java-Binary Search Tree Iterator
- Binary Search Tree Iterator (Java)
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- Binary Search Tree Iterator
- linux tee 命令详解
- [省选前题目整理][HDU 2512]一卡通大冒险(第二类斯特林数+贝尔数)
- ASP.NET MVC 文件上传和路径处理总结
- 高效人士睡前10件事
- 考研英语单词10—181-200
- [Java]leetcode173 Binary Search Tree Iterator
- Linux下常用压缩格式的压缩与解压方法
- 从头到尾彻底理解KMP
- 关于XCode6应用沙盒路径及NSHomeDirectory和NSSearchPathForDirectoriesInDomains
- linux下cron定时任务的总结
- Circular points at infinity
- Android SD卡路径问题以及如何获取SDCard 内存
- yii2学习笔记——03php5.4和php5.3的测试
- PC_excel异常大