题目:

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的更多相关文章

  1. 二叉树前序、中序、后序非递归遍历 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 前序的非递归遍历:用堆来实现 如果把这个代码改成先向堆存储左节点再存储右节点,就变成了每一行从右向左打印 如果用队列替代堆,并且 ...

  2. 【LeetCode】173. Binary Search Tree Iterator (2 solutions)

    Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...

  3. ✡ leetcode 173. Binary Search Tree Iterator 设计迭代器(搜索树)--------- java

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  4. leetcode 173. Binary Search Tree Iterator

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  5. 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 ...

  6. leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)

    https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary searc ...

  7. [leetcode]173. Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  8. 173. Binary Search Tree Iterator -- 迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  9. LC 173. Binary Search Tree Iterator

    题目描述 Implement an iterator over a binary search tree (BST). Your iterator will be initialized with t ...

随机推荐

  1. 翻转单词顺序VS左旋转字符串

    题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变.句子中单词以空格符隔开.为简单起见,标点符号和普通字母一样处理.例如输入“I am a student.”,则输出“student ...

  2. template_11实参演绎

    1,演绎过程匹配类型A(来自实参的类型),参数化类型P(行参参数声明)如果被声明的参数是一个引用声明g(T& )那么P就是所引用类型T:f(T)中P就是所声明的参数类: decay指从数组和函 ...

  3. [转]WINDOW进程间数据通讯以及共享内存

    1.引言 在Windows程序中,各个进程之间常常需要交换数据,进行数据通讯.WIN32 API提供了许多函数使我们能够方便高效地进行进程间的通讯,通过这些函数我们可以控制不同进程间的数据交换,就如同 ...

  4. Android 核心组件 Activity 之上

    核心组件的特征 1. 必须继承自特定的类(Activity 或者 Activity的子类) 2. 必须注册: 通常是AndroidManifest.xml的 <application> 中 ...

  5. asp.net 点击按钮,页面没有任何变化,后台代码不触发

    asp.net 点击按钮,页面没有任何变化,后台代码不触发 和可能是 asp.net button  缺少validationGroup 导致的,需要查看页面的validation并且让他们抛出错误信 ...

  6. syntaxhighlighter语法高亮

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xht ...

  7. memcache的一致性hash算法

    <?php /** * 一致性哈希memcache分布式,采用的是虚拟节点的方式解决分布均匀性问题,查找节点采用二分法快速查找 * the last known user to change t ...

  8. PHP获取IP及地区信息(纯真IP数据库)

    昨天在写程序的时候,发现在用户的时候记录IP和地区信息也许以后用得上,去网上找了找,发现实现的方式有好多好多,因为我用的ThinkPHP,后来又去TP官网找了找,最后采用了下面这种方法. <?p ...

  9. 1020. Tree Traversals (序列建树)

    Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and i ...

  10. C#网络编程简单实现通信小例子-2

    1.主界面  2.源代码                                                         Client public partial class For ...