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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Show Tags
Have you met this question in a real interview?

Yes
No
 

Discuss

SOLUTION 1:

使用inorder traversal把tree转化为arraylist.

递归

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ public class BSTIterator {
ArrayList<TreeNode> list;
int index; public BSTIterator(TreeNode root) {
list = new ArrayList<TreeNode>();
iterator(root, list); index = 0;
} // solution 1: recursion.
public void dfs (TreeNode root, ArrayList<TreeNode> ret) {
if (root == null) {
return;
} //Use inorder traversal.
dfs(root.left, ret);
ret.add(root);
dfs(root.right, ret);
} /** @return whether we have a next smallest number */
public boolean hasNext() {
if (index < list.size()) {
return true;
} return false;
} /** @return the next smallest number */
public int next() {
return list.get(index++).val;
}
} /**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/

SOLUTION 2:

the iterator version.

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ public class BSTIterator {
ArrayList<TreeNode> list;
int index; public BSTIterator(TreeNode root) {
list = new ArrayList<TreeNode>();
iterator(root, list); index = 0;
} // solution 2: Iterator.
public void iterator (TreeNode root, ArrayList<TreeNode> ret) {
if (root == null) {
return;
} Stack<TreeNode> s = new Stack<TreeNode>();
// bug 1: use push instead of put
TreeNode cur = root; while (true) {
// bug 2: should push the node into the stack.
while (cur != null) {
s.push(cur);
cur = cur.left;
} if (s.isEmpty()) {
break;
} // bug 3: should pop a node from the stack.
// deal with the top node in the satck.
cur = s.pop(); // bug 2: should be cur not root.
ret.add(cur);
cur = cur.right;
}
} /** @return whether we have a next smallest number */
public boolean hasNext() {
if (index < list.size()) {
return true;
} return false;
} /** @return the next smallest number */
public int next() {
return list.get(index++).val;
}
} /**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/

LeetCode: Binary Search Tree Iterator 解题报告的更多相关文章

  1. 【LeetCode】173. Binary Search Tree Iterator 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 保存全部节点 只保留左节点 日期 题目地址:http ...

  2. 【原创】leetCodeOj --- Binary Search Tree Iterator 解题报告

    时间挤挤总是有的 太久不做题,脑子都生锈了.来道水题练练手 题目地址: https://leetcode.com/problems/binary-search-tree-iterator/ 题目内容: ...

  3. [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

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

  4. LeetCode Binary Search Tree Iterator

    原题链接在这里:https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a bina ...

  5. LeetCode——Binary Search Tree Iterator

    Description: Implement an iterator over a binary search tree (BST). Your iterator will be initialize ...

  6. [LeetCode] Binary Search Tree Iterator 深度搜索

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

  7. 【LeetCode】270. Closest Binary Search Tree Value 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetco ...

  8. leetcode Binary Search Tree Iterator python

    # Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = ...

  9. 【LeetCode】95. Unique Binary Search Trees II 解题报告(Python)

    [LeetCode]95. Unique Binary Search Trees II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzh ...

随机推荐

  1. linux sshd ssh 服务的启动和使用

    这里使用sshd服务登录到linux系统的方法,不少同学走了弯路,包括我,我一直使用vmware虚拟linux学习使用的,后来windows病毒的原因转入到linux系统中使用 1,sshd服务安装 ...

  2. 浅谈bitmap算法

    一.bitmap算法思想 32位机器上,一个整形,比如int a; 在内存中占32bit位,可以用对应的32bit位对应十进制的0-31个数,bitmap算法利用这种思想处理大量数据的排序与查询.  ...

  3. HDU 4576 Robot (概率 & 期望)

    Robot Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 102400/102400 K (Java/Others)Total Sub ...

  4. 基于matplotlib的数据可视化 - 三维曲面图gca

    1 语法 ax = plt.gca(projection='3d')ax.plot_surface(x,y,z,rstride=行步距,cstride=列步距,cmap=颜色映射) gca(**kwa ...

  5. 安卓7.0遇到 android.os.FileUriExposedException: file:///storage/emulated.. exposed beyond app through Intent.getData()

    1.在AndroidManifest.xml中添加如下代码 <?xml version="1.0" encoding="utf-8"?> <m ...

  6. C++ 虚函数表浅析

    一.背景知识(一些基本概念) 虚函数(Virtual Function):在基类中声明为 virtual 并在一个或多个派生类中被重新定义的成员函数. 纯虚函数(Pure Virtual Functi ...

  7. 还没被玩坏的robobrowser(5)——Beautiful Soup的过滤器

    背景 本节的知识还是属于Beautiful Soup的内容. Beautiful Soup的find和find_all方法非常强大,他们支持下面一些类型的过滤器. 字符串 最简单的过滤器是字符串.在搜 ...

  8. 记github上搭建独立域名的免费博客的方法过程

    前提:拥有github帐号,linux上安装好了git. 全局路线: 1. 设计一个你想要的二级域名,并在git上创建一个以[二级域名.github.com]作为项目名的repository. 过程详 ...

  9. 用SQL语句将远程SQL Server数据库中表数据导入到本地数据库相应的表中

    一.方法一 访问不同电脑上的数据库(远程访问,只好联好网就一样),如果经常访问或数据量较大,建议用链接服务器方法. 1.创建链接服务器 exec sp_addlinkedserver ‘srv_lnk ...

  10. Sublime text —— 自定义主题Soda

    编辑器的主题有两种,一种是语法高亮颜色主题,一种是编辑器自身显示主题,如果要自定义编辑器样式,个人推荐soda. Ctrl+Shift+p 输入install,接着输入  soda,选择  Theme ...