LeetCode Binary Search Tree Iterator
2015-12-04 10:38
363 查看
题目:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
run in average O(1) time and uses O(h) memory, where h is the height of the tree.
例子:
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
题意:就是和上一题一样,在一棵二叉搜索树中,依次返回每个最小的值,此题就是典型的用递归来先序遍历得到结果,然后就是用一个判断是否存在下一个值,若存在,那么就直接再输出,否则就返回空。要求写两个函数,判断是否还存在的和取值的函数。
public class BSTIterator
{
ArrayList<Integer> list = new ArrayList<Integer>(); //全局变量非常好
int i = 0;
public BSTIterator(TreeNode root)
{
dfs(root);
}
public void dfs(TreeNode root)
{
if(root == null)
return;
else
{
if(root.left != null)
dfs(root.left);
list.add(root.val);
if(root.right != null)
dfs(root.right);
}
}
/** @return whether we have a next smallest number */
public boolean hasNext()
{
int length = list.size(); //注意,这里采用判断是否这个小于list的长度
if(i < length)
return true;
else
return false;
}
/** @return the next smallest number */
public int next()
{
int result = list.get(i).intValue(); //考虑返回
i++; //并且在这里加1
return result;
}
}此题,和之前我博客中的那题异曲同工,可以对比着看。
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.
例子:
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
题意:就是和上一题一样,在一棵二叉搜索树中,依次返回每个最小的值,此题就是典型的用递归来先序遍历得到结果,然后就是用一个判断是否存在下一个值,若存在,那么就直接再输出,否则就返回空。要求写两个函数,判断是否还存在的和取值的函数。
public class BSTIterator
{
ArrayList<Integer> list = new ArrayList<Integer>(); //全局变量非常好
int i = 0;
public BSTIterator(TreeNode root)
{
dfs(root);
}
public void dfs(TreeNode root)
{
if(root == null)
return;
else
{
if(root.left != null)
dfs(root.left);
list.add(root.val);
if(root.right != null)
dfs(root.right);
}
}
/** @return whether we have a next smallest number */
public boolean hasNext()
{
int length = list.size(); //注意,这里采用判断是否这个小于list的长度
if(i < length)
return true;
else
return false;
}
/** @return the next smallest number */
public int next()
{
int result = list.get(i).intValue(); //考虑返回
i++; //并且在这里加1
return result;
}
}此题,和之前我博客中的那题异曲同工,可以对比着看。
相关文章推荐
- 拥抱高效、拥抱 Bugtags 之来自用户的声音 2
- 关注的几个游戏引擎
- Cocos2D-x HelloWorld代码执行过程
- memcached 中继主从延迟数据
- asp.net文件/大文件上传需要配置的项目整理
- 原生js版ajax请求
- LintCode-剑指Offer-(4)丑数
- jQuery旋转木马式幻灯片轮播特效
- 官方渠道ios应用审核加速@AppStore上架加速
- linux如何使用iptables进行本地端口转发
- 开启我的博客园之路
- linux下杀死进程(kill)的N种方法
- ubuntu下编译contiki
- easyui 动态生成datagrid列
- 【收藏帖】windows和Linux的数据类型对比
- java调用Properties文件
- 链接集锦
- selenium获取html的表格单元格数据
- RedHat 6.5 Puppet配置[troubleshooting]
- 判断iphone设备型号