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 ...
随机推荐
- LeetCode:路径总和【112】
LeetCode:路径总和[112] 题目描述 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和. 说明: 叶子节点是指没有子节点的节点. 示例 ...
- 在freescale mx6q平台上添加spi资源
1:配置管脚为SPI功能 在board-mx6q_sabresd.h的最后添加,复制被重定义 (以添加SPI2为例) <span style="font-size:18px;" ...
- 测试连接oracle数据库耗时
maven项目 主程序:ConnOracle.java package org.guangsoft.oracle; import java.sql.Connection; import java.sq ...
- python日志操作logging
步骤: 1.定义一个日志收集器 my_logger = logging.getLogger("kitty") 2.设定级别.默认为warning:debug,,info,error ...
- Hearbeat 工作原理
Hearbeat 原理 heartbeat (Linux-HA)的工作原理:heartbeat最核心的包括两个部分,心跳监测部分和资源接管部分,心跳监测可以通过网络链路和串口进行,而且支持冗 余链路, ...
- 跨平台移动开发_PhoneGap API Camera 使用摄像头采集照片.
camera对象提供对设备默认摄像头应用程序的访问. 程序运行效果 相关代码 <!DOCTYPE html> <html> <head> <title> ...
- python的常用的内置函数
使用内置函数的好处:简单,快速. 1.zip():以多个序列为参数,返回元祖列表. 长度:在多个序列长度不一时,以最短的为准. 常见用途:构建多参数列表,构建字典. 2.map():在python2旧 ...
- CoreData的基本操作
Managed Object Model(被管理对象模型): –数据库的轮廓,或者结构.包含了各个实体的定义信息 Persistent Store Coordinator (持久性数据协调 ...
- pache—DBUtils框架简介、DbUtils类、QueryRunner类 、ResultSetHandler接口
Apache—DBUtils框架简介.DbUtils类.QueryRunner类 .ResultSetHandler接口 commons-dbutils 是 Apache 组织提供的一个开源 JDBC ...
- WINDOWS下好用的MongoDB 3.0以上客户端工具: NoSql Manager
WINDOWS下好用的MongoDB 3.0以上客户端工具: NoSql Manager https://www.mongodbmanager.com/download