题目:

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. vs2008+qt进行开发

    第一次接触qt vs,完全小白,网上找资料,各种乱,还大部分是很早以前的,挣扎了好几天终于搞定了, 在此给大家分享. 首先是下载vs2008 (我的项目组项目要求用这个版本),这个比较容易下载:然后是 ...

  2. C++与Lua交互(一)

    引言 之前做手游项目时,客户端用lua做脚本,基本所有游戏逻辑都用它完成,玩起来有点不爽,感觉"太重"了.而我又比较偏服务端这边(仅有C++),所以热情不高.最近,加入了一个端游项 ...

  3. wall time和monotonic time[转载]

    在一些系统调用中需要指定时间是用CLOCK_MONOTONIC还是CLOCK_REALTIME,以前总是搞不太清楚它们之间的差别,现在终于有所理解了.     CLOCK_MONOTONIC是mono ...

  4. Android SDK Manager国内无法更新的解决方案

    万里长城永不倒,千里黄河水滔滔.算了跑题了. 但还是要吐槽这下这个万里长城,感谢 方滨兴 叫兽 给我们净化了互联网,靠!什么&!@#¥ 此处略去一万字. 现在由于GWF,google基本和咱们 ...

  5. JQGrid+Nhibernate+Webservice+Linq

    先上效果图:   前台代码(jqgridtest.aspx): <%@ Page Language="C#" AutoEventWireup="true" ...

  6. wireshark总结

    拖延了两个月的总结!下面的很大一部分来自其它博客. wireshark过滤器的区别 捕捉过滤器(CaptureFilters):用于决定将什么样的信息记录在捕捉结果中.需要在开始捕捉前设置.在Capt ...

  7. JS的IE和FF兼容性问题汇总

    转自:蓝色理想 以下以 IE 代替 Internet Explorer,以 MF 代替 Mozilla FF 一.函数和方法差异 1. getYear()方法 [分析说明]先看一下以下代码: var ...

  8. 纯JS焦点图特效(可一个页面多用)

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

  9. H5全景视频VR视频

    公司的有个专题页面涉及到全景视频展示这个技术点,找到一个相关的库. http://www.utovr.com/sdk/download  这里有个免费的SDK可以下载. 里面也有案例可以看,代码就照着 ...

  10. window.onbeforeunload 如果取消, 那么javascript变量会保存

    function confirmQuit1() { if (ischanged) return 'it is changed !! '; else return 'no change .. '; } ...