[LeetCode] Binary Search Tree Iterator
2015-08-14 14:13
357 查看
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
中午下雨了。于是木有吃午饭(=。=)现在有点饿。
这个比较难的就是next() method了,就是喊你返回BTS中最小的那个数。
然后很容易的,我们要先建一个不管是List,stack还是神马的,反正拿来store每个结点最小的数就行了。(一般情况下就是最左边的那个数)
当然呢如果最左边刚好null呢?我们第一次store的时候就肯定会在这里停下了,因此我们需要检查右边是否null,如果右边不是null的,那么就检查这个右边的treenode左边是否null,如果是,继续接着往下…………
代码如下。~
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.
中午下雨了。于是木有吃午饭(=。=)现在有点饿。
这个比较难的就是next() method了,就是喊你返回BTS中最小的那个数。
然后很容易的,我们要先建一个不管是List,stack还是神马的,反正拿来store每个结点最小的数就行了。(一般情况下就是最左边的那个数)
当然呢如果最左边刚好null呢?我们第一次store的时候就肯定会在这里停下了,因此我们需要检查右边是否null,如果右边不是null的,那么就检查这个右边的treenode左边是否null,如果是,继续接着往下…………
代码如下。~
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { List<TreeNode> tree; public BSTIterator(TreeNode root) { tree=new ArrayList<TreeNode>(); while(root!=null){ tree.add(root); root=root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !tree.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode min=tree.remove(tree.size()-1); TreeNode temp=min.right; while(temp!=null){ tree.add(temp); temp=temp.left; } return min.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
相关文章推荐
- spring中bean的获取方式总结
- 用python合并N个不同字符集编码的sql文件的实践
- uva 1471 Defense Lines
- jQuery文档处理,外部插入
- c#读取数据库中图片路径,将图片保存到imagelist,在listview显示
- Cubietruck---3. android编译命令分析
- JAVA常见错误处理方法
- java 调用webservice的各种方法总结,wsimport方法总结
- cisco交换telnet、http登陆配置及安全加固ACL实例
- Shader的亮度brightness、饱和度saturation、对比度contrast算法
- 开源中最好的Web开发资源汇总
- 自适应网页设计
- Wireless Network
- android面试经验谈
- 抽牌算法
- 使用SWPM安装 SAP ERP6.0 on solaris 10
- Shell编程和Vim操作
- Wireless Network
- Search for a Range
- Kurento应用开发指南(以Kurento 5.0为模板) 之二:示例教程helloworld