LeetCode OJ: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.
相当于遍历二叉搜索树,借助栈即可实现:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/ class BSTIterator {
private:
stack<TreeNode *> stk;
TreeNode * node;
public:
BSTIterator(TreeNode *root) {
node = root;
} /** @return whether we have a next smallest number */
bool hasNext() {
return (node || !stk.empty());
} /** @return the next smallest number */
int next() {
TreeNode * res = NULL;
if(node == NULL){
res = stk.top();
stk.pop();
node = res->right;
}else{
while(node->left != NULL){
stk.push(node);
node = node->left;
}
res = node;
node = node->right;
}
return res->val;
}
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
或者可以看看另一种做法,就是在构造迭代器的时候就将第一个最小的值准备好,不过二者的思路大体是一样的:
class BSTIterator {
private:
stack<TreeNode *> s;
public:
BSTIterator(TreeNode *root) {
while(root){
s.push(root);
root == root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !s.empty();
}
/** @return the next smallest number */
int next() {
TreeNode * n = s.top();
ret = n.val;
s.pop();
n = n->right;
while(n){
s.push(n);
n = n->left;
}
return res;
}
};
或者就是直接的开始的时候就进行中序遍历,然后装入一个队列,需要的时候直接pop就可以了:
class BSTIterator {
public:
queue<int> q;
map<TreeNode *, bool> m;
stack<TreeNode *> s;
BSTIterator(TreeNode *root) {
if(root)
s.push(root);
while(!s.empty()){
TreeNode * t = s.top();
if(t->left && m[t->left] == false){
s.push(t->left);
m[t->left] = true; //表示这条路已经报错过了,下次走的不经过这里
continue;
}
q.push(t->val);
s.pop();
if(t->right && m[t->right] == false){
s.push(t->right);
m[t->right] = true;
}
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(!q.empty())
return true;
return false;
}
/** @return the next smallest number */
int next() {
if(hasNext()){
int t = q.front();
q.pop();
return t;
}
}
};
java版本的如下所示,首先是用一个Stack来实现的:
public class BSTIterator {
Stack<TreeNode> s;
TreeNode n;
public BSTIterator(TreeNode root) {
s = new Stack<TreeNode>();
n = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return n != null || !s.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode res = null;
if(n == null){
n = s.pop();
res = n;
n = n.right;
}else{
while(n.left != null){
s.push(n);
n = n.left;
}
res = n;
n = n.right;
}
return res.val;
}
}
另一个的版本也如下所示,同样是将所有的数字再构造的时候就中序遍历完成,然后的hasNext以及next就非常简单了。
public class BSTIterator {
Queue<Integer> queue;
Stack<TreeNode> stack;
HashMap<TreeNode, Integer> map; //表示这个Node是否已经在queue存在着了,0表示没有,1表示已经存在了
public BSTIterator(TreeNode root) { //对象构造的时候将所有的值就全部的装入了一个队列中
queue = new LinkedList<Integer>();
stack = new Stack<TreeNode>();
map = new HashMap<TreeNode, Integer>();
TreeNode node;
if(root == null)
return;
stack.push(root);
while(!stack.isEmpty()){
node = stack.peek();
while(node.left != null && !map.containsKey(node.left)){
stack.push(node.left);
map.put(node.left, 1);
node = node.left;
}
queue.add(node.val);
stack.pop();
if(node.right != null && !map.containsKey(node.right)){
stack.push(node.right);
map.put(node.right, 1);
}
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !queue.isEmpty();
}
/** @return the next smallest number */
public int next() {
return queue.poll();
}
}
LeetCode OJ:Binary Search Tree Iterator(二叉搜索树迭代器)的更多相关文章
- [leetcode]173. Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- 173 Binary Search Tree Iterator 二叉搜索树迭代器
实现一个二叉搜索树迭代器.你将使用二叉搜索树的根节点初始化迭代器.调用 next() 将返回二叉搜索树中的下一个最小的数.注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 ...
- Leetcode173. Binary Search Tree Iterator二叉搜索树迭代器
实现一个二叉搜索树迭代器.你将使用二叉搜索树的根节点初始化迭代器. 调用 next() 将返回二叉搜索树中的下一个最小的数. 注意: next() 和hasNext() 操作的时间复杂度是O(1),并 ...
- [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- [LeetCode] Recover Binary Search Tree 复原二叉搜索树
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- [LeetCode] Validate Binary Search Tree 验证二叉搜索树
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...
- [Leetcode] Recover binary search tree 恢复二叉搜索树
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...
- [CareerCup] 4.5 Validate Binary Search Tree 验证二叉搜索树
4.5 Implement a function to check if a binary tree is a binary search tree. LeetCode上的原题,请参见我之前的博客Va ...
- [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree (二叉搜索树最近的共同祖先)
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
随机推荐
- 剑指offer 面试61题
面试61题: 题目:LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到 ...
- Android下Opengl ES实现单屏幕双眼显示
http://blog.csdn.net/u011371324/article/details/68946779 默认情况下,Opengl ES使用系统提供的帧缓冲区作为绘图表面,一般情况下,如果只在 ...
- 【Flask】Flask-Sqlalchemy使用笔记
### 安装:```shellpip install flask-sqlalchemy``` ### 数据库连接:1. 跟sqlalchemy一样,定义好数据库连接字符串DB_URI.2. 将这个定义 ...
- pearson相关分析在R中的实现
三个相关性函数: cor():R自带的,输入数据可以是vector,matrix,data.frame,输出两两的相关系数R值 cor.test():R自带的,输入数据只能是两个vector,输出两个 ...
- linux下安装eclipse并使用xstart远程使用(centos7)
1 eclipse安装 1)到官网下载eclipse的linux版 http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-deve ...
- ubuntu 的mysql 安装过程和无法远程的解决方案
ubuntu 的mysql 安装过程和无法远程的解决方案 安装完mysql-server启动mysqlroot@ubuntu:# /etc/init.d/mysql start (如果这个命令不可以, ...
- CCNA 课程 二
传输层:两个重要的协议 TCP 和 UDP TCP: 面向连接的协议:在传输用户数据前,先要建立连接 (TCP的三次握手) 错误检查 数据包序列化 可靠性传输:发送的数据需要接受者提供确认,通过报头中 ...
- MapReduce-排序(全部排序、辅助排序)
排序 排序是MapReduce的核心技术. 1.准备 示例:按照气温字段对天气数据集排序.由于气温字段是有符号的整数,所以不能将该字段视为Text对象并以字典顺序排序.反之,用顺序文件存储数据,其In ...
- hadoop 指定 key value分隔符
原文:http://wingmzy.iteye.com/blog/1260570 hadoop中的map-reduce是处理<key,value>这样的键值对,故指定<key,val ...
- Ubuntu下用crontab 部署定时任务
用php做了一个网站,其中一个统计工能,需要每周定时用行.想看看有什么方法,之前看别人的东西,一般有2中方式,一个是php自带的定时任务,一个是用系统 带的,linux下的crontab和window ...