173. 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.
链接: http://leetcode.com/problems/binary-search-tree-iterator/
题解:
二叉搜索树iterator,要求O(1)的next()和hasNext()。可以用in-order traversal。
再仔细看一看,要求O(h)的memory,这样二刷的时候还要再仔细想一想。还有Morris Traversal要学习.
Time Complexity of next() and hasNext() - O(1), Space Complexity - O(n)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ public class BSTIterator {
private Queue<Integer> queue; //left, mid ,right public BSTIterator(TreeNode root) {
this.queue = new LinkedList<>();
inOrderTraversal(root);
} private void inOrderTraversal(TreeNode root) {
if(root == null)
return; Stack<TreeNode> stack = new Stack<>();
while(root != null || !stack.isEmpty()) {
if(root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
queue.offer(root.val);
root = root.right;
}
}
} /** @return whether we have a next smallest number */
public boolean hasNext() {
return !queue.isEmpty();
} /** @return the next smallest number */
public int next() {
if(hasNext())
return queue.poll();
return Integer.MAX_VALUE;
}
} /**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
二刷:
一刷写得不智慧。注意这里题目要求是amortized complexity - O(1)。是total expense of one operation。所以我们可以用把in-order traversal分解为左右两部分,然后分别放入stack中,就可以满足题目要求了。
为什么是amortized O(1)呢? 因为在我们遍历整个树的过程中,对每个节点都只push 1次,所以对于遍历n个节点的树,我们总的expense是 O(n),那amortized complexity就等于 O(1)了。
空间复杂度的减少,最好还是用Morris-traversal,下一次一定要好好写一遍。
Java:
Time Complexity: next() - amortized O(1), hasNext() - O(1), Space Complexity - O(h)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ public class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
inorder(root);
} /** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
} /** @return the next smallest number */
public int next() {
TreeNode root = stack.pop();
inorder(root.right);
return root.val;
} private void inorder(TreeNode root) {
while (root != null) {
stack.push(root);
root = root.left;
}
}
} /**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
Reference:
https://leetcode.com/discuss/20001/my-solutions-in-3-languages-with-stack
https://leetcode.com/discuss/20101/ideal-solution-using-stack-java
https://leetcode.com/discuss/30207/my-simple-solution-here
https://leetcode.com/discuss/23721/morris-traverse-solution
http://stackoverflow.com/questions/15079327/amortized-complexity-in-laymans-terms
https://en.wikipedia.org/wiki/Amortized_analysis
173. Binary Search Tree Iterator的更多相关文章
- 二叉树前序、中序、后序非递归遍历 144. Binary Tree Preorder Traversal 、 94. Binary Tree Inorder Traversal 、145. Binary Tree Postorder Traversal 、173. Binary Search Tree Iterator
144. Binary Tree Preorder Traversal 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...
- 【LeetCode】173. Binary Search Tree Iterator (2 solutions)
Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...
- ✡ leetcode 173. Binary Search Tree Iterator 设计迭代器(搜索树)--------- java
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- leetcode 173. Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- Java for LeetCode 173 Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)
https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary searc ...
- [leetcode]173. Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- 173. Binary Search Tree Iterator -- 迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- LC 173. Binary Search Tree Iterator
题目描述 Implement an iterator over a binary search tree (BST). Your iterator will be initialized with t ...
随机推荐
- C/C++ union
叙述原因: union data{ int a;double b;}; 对于union,实际中用的并不多,之前也知道怎样计算union的单元(在字对齐的基础上取最大成员所占的内存大小),比如 unio ...
- js 的数据类型转换
一直对js的类型转换一直半解,今天理一下思路,首先说一下几个特殊的数值 null null是特殊的object,故 typeof null 返回object, null派生于undefined ,故 ...
- Android使用百度地图API实现GPS步行轨迹
百度地图Android SDK下载:http://developer.baidu.com/map/sdkandev-download.htm 下面是效果: 采样点取得太频繁所以看起来像是一个个点... ...
- Demo学习: Cookies Demo
Cookies Demo 浏览器Cookies的读写,最常用的就是记录用户的登录信息,在项目里做登录界面时也用到了Cookies功能. procedure TMainForm.UniButton2Cl ...
- Python操作RabbitMQ初体验(一)
由于想用Python实现一套分布式系统,来管理和监控CDN的内容与运行状态,误打误撞认识了RabbitMQ,推荐的人很多,如余锋<我为什么要选择RabbitMQ>等等. 在MQ这个词汇映入 ...
- mac 下 sphinx + mysql + php 实现全文搜索(xampp)(4)php api 解析
1:function GetLastError() // 假如报错的话,会输出报错信息 2:function GetLastWarning ()// 输出 警告信息 3:function SetSe ...
- php + mysql + sphinx 的全文检索(2)
简单 使用php api 去查询 sphinx 的索引数据 $sphinx = new SphinxClient(); $sphinx->SetServer ( ...
- 理解UIEdgeInsets
供参考 iOS 的控件,只看到 UIButton 可以设置 Padding/Insets,即按钮上文字或图片与按钮边界的间隙. CSS 上叫做 Padding,在 iOS 中叫做 Insets,UIB ...
- Telerik_2012_Q3 (已破解)全套下载链接
1.Telerik_OpenAccess_ORM_2012_3_1012_SDK.zip (暂未提供下载) 2. Telerik_OpenAccess_ORM_2012_3_1012.zip 3. T ...
- 基于Ogre的DeferredShading(延迟渲染)的实现以及应用
http://blog.sina.com.cn/s/blog_458f871201017i06.html 这篇文章写的不错,从比较宏观的角度说了下作者在OGRE中实现的延迟渲染