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 ...
随机推荐
- 多进程之间的互斥信号量实现(Linux和windows跨平台)
多线程之间实现互斥操作方式很多种,临界区(Critical Section),互斥量(Mutex),信号量(Semaphore),事件(Event)等方式 其中临界区,互斥量,信号量算是严格意义的实现 ...
- Poj 2262 / OpenJudge 2262 Goldbach's Conjecture
1.Link: http://poj.org/problem?id=2262 http://bailian.openjudge.cn/practice/2262 2.Content: Goldbach ...
- java学习笔记_MIDI_GUI
import javax.sound.midi.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; class M ...
- DTCMS规格统一赋值
admin\article_edit.aspx 已经存在 市场价格 和销售价格统一赋值 //赋值规格市场价格 $("#field_control_market_price").bl ...
- asp.net runat="server" && hiddenfield
runat="server", c#可以直接获得client控件,并且赋值 hiddenfield 可以作为传值,或者界面存值,后台每次读取,并且再赋值到前台,这样前台就可以把上一 ...
- javascript截取字符串(支持中英文混合)
javascript截取字符串(支持中英文混合) <script type="text/javascript"> var sub=function(str,n){ va ...
- SQL Server 2008 安装或卸载时提示“重启计算机失败"的解决办法(转)
安装或卸载SQL Server 遇到错误提示:以前的某个程序安装已在安装计算机上创建挂起的文件操作.运行安装程序之前必须重新启动计算机.如下图: 解决办法: 1.在开始->运行中输入regedi ...
- DIV当textarea使用,在聚焦的时候将光标移动到内容的末尾
#### DIV当textarea使用,在聚焦的时候将光标移动到内容的末尾 #### <style type="text/css"> .test_box { width ...
- java 中的异常处理
一. 异常的概念和Java异常体系结构 异常是程序运行过程中出现的错误.本文主要讲授的是Java语言的异常处理.Java语言的异常处理框架, 是Java语言健壮性的一个重要体现. Java把 ...
- FPGA位宽的转换和定义
数字表达式的定义<位宽><进制><数字>,这是一种全面的描述方式 例如:如果我要定义一个变量counter = 5000 0000 ,10进制数:那么他的位宽应该是 ...