题目:

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. C++链式继承

            继承,对于学习C++的每一个人来说,都不会陌生.在Qt的开发中,如果你需要对一个无边框的界面支持move操作,那么你就得通过继承重写虚函数来实现,这并不难,但如果我还需要对一个按钮支持 ...

  2. DTCMS中文章增加tags标签和关键词时中文,替换为英文状态,

    DTCMS.Web\admin\article\article_edit.aspx 找到添加和修改的方法 model.tags = txtTags.Text.Trim()model.seo_keywo ...

  3. AngularJS(9)-表单

    AngularJS 表单是输入控件的集合 <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

  4. PHP服务器负载判断

    <?php header("content-type:text/html;charset=utf-8"); // echo PHP_OS;exit; // echo get_ ...

  5. [大牛翻译系列]Hadoop(1)MapReduce 连接:重分区连接(Repartition join)

    4.1 连接(Join) 连接是关系运算,可以用于合并关系(relation).对于数据库中的表连接操作,可能已经广为人知了.在MapReduce中,连接可以用于合并两个或多个数据集.例如,用户基本信 ...

  6. Arcgis 10.1 求面里面所包含的点的平均值

    空间链接的作用:将面上的所有点的值加起来取平均值。赋值给面属性。(我们可以定义右击——定义合并规则 连接要素的字段映射参数中指定的合并规则仅适用于连接要素中的属性,且仅适用于多个要素与目标要素匹配   ...

  7. 十六、mysql 分区之 简单sql优化2

    .索引的分类 B-Tree 基本支持 HASH 只有memory支持 R-Tree myisam支持 Full-text myisam支持(全文索引) .Memory引擎下只有“=”条件才会使用索引 ...

  8. 【maven项目结构】module 生成独立的jar

    生成jar 生成jar的过程会出现以下问题: clean完了之后就会出现以下问题: install [INFO] Scanning for projects... [INFO] [INFO] ---- ...

  9. PS 颜色表大全-颜色中文名(1)

    颜色中文名  鸨色#f7acbc 赤白橡#deab8a 油色#817936 绀桔梗#444693 踯躅色#ef5b9c 肌色#fedcbd 伽罗色#7f7522 花色#2b4490 桜色#feeeed ...

  10. 玩转Log4Net

    玩转Log4Net 下载Log4Net 下载地址:http://logging.apache.org/log4net/download_log4net.cgi 把下载的  log4net-1.2.11 ...