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 ...
随机推荐
- ios 避免两个button同一时候被点击
版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/superchaoxian/article/details/24631293 这个能够通过[btn ...
- Redis3.2.8配置参数及说明
bind 127.0.0.1# 绑定的主机地址,不设置默认将处理所有请求protected-mode yes# 是否开启保护模式,默认开启,要是配置里面没有指定bind和密码,开启该参数后,redis ...
- C++实现计算器功能(包括计算含未知量的式子),输出后缀表达式
大概描述 用c++语言在vc中实现部分数学计算功能.其中实现的数学计算功能包括加减乘除运算.开方计算.自然对数运算.以10为底的对数运算.幂计算.正弦余弦计算. 由用户输入要计算的表达式 ...
- Django设置上传文件夹
django提供了两种字段类型models.FileField与models.ImageField,用于保存上传文件与图象.这两类字段提供了一个参数'upload_to',用于定义上传文件保存的路径( ...
- PHP......会话控制SESSION与COOKIE
一.SESSION Session:在计算机中,尤其是在网络应用中,称为“会话控制”.Session 对象存储特定用户会话所需的属性及配置信息.这样,当用户在应用程序的 Web 页之间跳转时,存储在 ...
- iOS 52个技巧学习心得笔记 第一章 熟悉OC
1 .简单了解OC2 .在类的头文件中尽量少引入其他头文件3 .多用字面量语法 少用与之等价的方法 4 .多用类型常量 少用 #define 预处理指令5 .用枚举表示状态,选项,状态码 .简单了解O ...
- Linux基本命令 文件处理命令
概述 命令格式:命令 [-选项] [参数] 例如:ls -la /etc 说明:1.个别命令使用不遵守此格式.2. 当有多个选项时,可以写在一起. ls 命令示例 文件打印命令cat.tac.more ...
- css背景透明文字不透明
测试背景透明度为0.3.文字不透明: background-color: #000; /* 一.CSS3的opacity */ opacity: 0.3; /* 兼容浏览器为:firefox,chro ...
- 0625 Django 基础
相关命令: 1 创建项目 django-admin startproject 项目名称 2 创建应用 python manage.py startapp app名称 3 启动项目 python man ...
- css transform常用变化解析
本文旨在对常用变化做最直观的简析 translate 移动 translateX() X轴正方向移动(单位可为px,也可为%,为%时以自身为参照物) translateY() Y轴反方向移动 tran ...