Binary Search Tree Iterator
2016-06-04 16:43
225 查看
题目描述:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
h is the height of the tree.
题目意思是设计一个迭代器,每次得到容器内最小的值。
一直往左子树走,就是最小值,然后看这个最小值有没有又子树且这个右子树之前没有被访问过,如果有右子树就接着往右子树的左子树走,没有的话弹出来看这个节点的父节点。
代码如下:
public class BSTIterator {
Stack<TreeNode> stack;
Set<TreeNode> visited;
public BSTIterator(TreeNode root) {
stack=new Stack<TreeNode>();
visited=new HashSet<TreeNode>();
stack.add(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(!stack.isEmpty()){
return stack.peek()==null?false:true;
}
return false;
}
public int next() {
TreeNode node=stack.peek();
while(node.left!=null&&!visited.contains(node.left)){
stack.add(node.left);
node=node.left;
}
node=stack.pop();
if(node.right!=null&&!visited.contains(node.right))
stack.add(node.right);
visited.add(node);
return node.val;
}
}
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.
题目意思是设计一个迭代器,每次得到容器内最小的值。
一直往左子树走,就是最小值,然后看这个最小值有没有又子树且这个右子树之前没有被访问过,如果有右子树就接着往右子树的左子树走,没有的话弹出来看这个节点的父节点。
代码如下:
public class BSTIterator {
Stack<TreeNode> stack;
Set<TreeNode> visited;
public BSTIterator(TreeNode root) {
stack=new Stack<TreeNode>();
visited=new HashSet<TreeNode>();
stack.add(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(!stack.isEmpty()){
return stack.peek()==null?false:true;
}
return false;
}
public int next() {
TreeNode node=stack.peek();
while(node.left!=null&&!visited.contains(node.left)){
stack.add(node.left);
node=node.left;
}
node=stack.pop();
if(node.right!=null&&!visited.contains(node.right))
stack.add(node.right);
visited.add(node);
return node.val;
}
}
相关文章推荐
- 汇编学习笔记
- Hibernate-动态查询Demo
- 约数国王(A king)
- 目录一
- Lightmass静态全局光照
- 解析堆和栈的区别
- python爬虫:批量下载qq空间里的照片(一)
- C语言大纲——C语言的概述
- JDK1.8 HashMap中put源码分析
- github 远程仓库
- ubuntu定时备份网站及数据库到备份服务器
- netlink socket编程实例
- EditTexts实现图文混排
- 符号与编码
- 手把手教你开发基于深度学习的人脸识别【考勤/签到】系统
- 自定义拖拽IndicatorView
- post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
- 什么是单元测试
- ListView的点击事件应用
- 链接和库