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. memcached完全剖析--1. memcached的基础

    翻译一篇技术评论社的文章,是讲memcached的连载.fcicq同学说这个东西很有用,希望大家喜欢. 发表日:2008/7/2 作者:长野雅广(Masahiro Nagano) 原文链接:http: ...

  2. JQuery UI - draggable(转)

    ·概述 在任何DOM元素启用拖动功能.通过单击鼠标并拖动对象在窗口内的任何地方移动. 官方示例地址:http://jqueryui.com/demos/draggable/ 所有的事件回调函数都有两个 ...

  3. 对于“Newtonsoft.Json”已拥有为“NETStander.Library”定义的依赖项,解决办法

    问题描述: 在使用visual studio中的NuGet包管理下载程序时,有时会出现-对于“Newtonsoft.Json”已拥有为“NETStander.Library”定义的依赖项,这样的错误. ...

  4. 【Struts2】Struts2框架的搭建

    1,Struts2简介 struts1和struts2都是由Apache组织发布的,但是比较有趣的是struts2和struts1并没有“血缘关系”.在Apache发布struts1之后,当时是还是非 ...

  5. android 点击通知栏返回应用 ,非启动一个新Activity

    再使用如下的 Intent 设置: Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ ...

  6. redis常用性能分析命令

    一.连接 src/redis-cli -h 10.20.137.141 -p 6379 >auth 123456789 src/redis-cli -h 10.20.137.141 -p 637 ...

  7. EasyUI 中GridView 满足某条件 改变行的背景色

    <table id='grid' class='easyui-datagrid' style='width:1500px;height:450px' url='Ajax-index.php?mo ...

  8. ajaxupload.js调用始终进入error回调

    现象:脚本调用成功,文件上传也成功,但是始终进入error的回调函数. 1. ajaxfileupload.js jQuery.extend({ handleError: function( s, x ...

  9. ldconfig命令

    ldconfig是一个动态链接库管理命令 为了让动态链接库为系统所共享,还需运行动态链接库的管理命令--ldconfigldconfig 命令的用途,主要是在默认搜寻目录(/lib和/usr/lib) ...

  10. js两个日期相减

    function dateHanle(d1,d2){ if(Date.parse(d1) - Date.parse(d2)==0) { console.log("d1等于d2"); ...