题目:

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. 分享一个难得的YiBo微博客户端应用源码Android版

    今天给大家分享一款,YiBo微博客户端应用源码,这是一款专为Android用户打造的聚合型微博客户端,完美支持新浪微博.腾讯微博.搜狐微博.网易微博和饭否五个微博平台,界面清爽,使用简单轻巧,支持多账 ...

  2. $设置背景图片的css

    $('.d-game-pic').css('background-image', 'url(' + App.getImg(gameDetail.desc_pic) + ')');

  3. php入门变量之数字

    在介绍变量时,我明确指出PHP具有整型和浮点型(小数)数字类型.但是,依据我的经验,这两种类型都可以归类到一般的数字之下(在极大程度上是这样的). 下面列举下PHP中有效的数字类型的变量: 8 3.1 ...

  4. phpcms v9 打开网站特别慢 增加数据库缓存方法

    SET GLOBAL QUERY_CACHE_SIZE=80000000; 设置好查询缓存的大小就行了.比如设置个20MB.SET GLOBAL QUERY_CACHE_SIZE=20000000; ...

  5. VB.Net 文件处理类

    1.编写日志 2.本地文件的读取和写入 3.Base64与图片的互相转换 Imports System.IO Imports System.Text Public Class Cls_File #Re ...

  6. Oracle SGA参数调整

    一. SGA的组成: 自动 SGA 管理后,Oracle 可以自动为我们调整以下内存池的大小: shared pool buffer cache large pool java pool stream ...

  7. linux 输入子系统(1)----系统概述

    输入设备的工作中,只是中断.读键值/坐标值是设备相关的,而输入事件的缓冲区管理以及字符设备驱动的file_operations接口则对输入设备是通用的,基于此,内核设计了input输入子系统,由核心层 ...

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

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

  9. go语言实现线程池

    话说真的好久没有写博客了,最近赶新项目,工作太忙了.这一周任务比较少,又可以随便敲敲了. 逛论坛的时候突发奇想,想用go语言实现一个线程池,主要功能是:添加total个任务到线程池中,线程池开启num ...

  10. [译] ASP.NET 生命周期 – ASP.NET 请求生命周期(三)

    使用特殊方法处理请求生命周期事件 为了在全局应用类中处理这些事件,我们会创建一个名称以 Application_ 开头,以事件名称结尾的方法,比如 Application_BeginRequest.举 ...