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(二叉搜索树迭代器)的更多相关文章

  1. [leetcode]173. Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  2. 173 Binary Search Tree Iterator 二叉搜索树迭代器

    实现一个二叉搜索树迭代器.你将使用二叉搜索树的根节点初始化迭代器.调用 next() 将返回二叉搜索树中的下一个最小的数.注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 ...

  3. Leetcode173. Binary Search Tree Iterator二叉搜索树迭代器

    实现一个二叉搜索树迭代器.你将使用二叉搜索树的根节点初始化迭代器. 调用 next() 将返回二叉搜索树中的下一个最小的数. 注意: next() 和hasNext() 操作的时间复杂度是O(1),并 ...

  4. [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  5. [LeetCode] Recover Binary Search Tree 复原二叉搜索树

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  6. [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 ...

  7. [Leetcode] Recover binary search tree 恢复二叉搜索树

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  8. [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 ...

  9. [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 ...

  10. 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 ...

随机推荐

  1. LATEX教程(一)

    第一个文档 打开WinEdt,建立一个新文档,将以下内容复制进入文档中,保存,保存类型选择为UTF-8. \documentclass{article} \begin{document} hello, ...

  2. Mybatis使用pageHelper步骤

    1.在pom.xml中添加如下依赖: <dependency> <groupId>com.github.pagehelper</groupId> <artif ...

  3. boost之日期date_time

    date_time库使用的日期基于格里高利历,支持从1400-01-01到9999-12-31的日期. 空的构造函数会创建一个值为not_a_date_time的无效日期:顺序传入年月日值则创建一个对 ...

  4. Java 如何读取resources

    Sample in Github 1.一般使用Maven创建Java工程,代码文件在src/main/java文件夹中,资源文件在src/main/resources文件夹中,Java代码为什么可以读 ...

  5. OpenGL学习进程(5)第三课:视口与裁剪区域

    本节是OpenGL学习的第三个课时,下面介绍如何运用显示窗体的视口和裁剪区域:     (1)知识点引入:     1)问题现象: 当在窗体中绘制图形后,拉伸窗体图形形状会发生变化: #include ...

  6. [原创]spring及springmvc精简版--AOP

    接上一篇:[原创]spring及springmvc精简版--IOC 理解AOP.java是一种面向对象的语言.而AOP是面向切面,在我看来是面向逻辑或者业务编程,它是对一组逻辑的抽象和分配. 经典例子 ...

  7. tophat的用法

    概述:tophat是以bowtie2为核心的一款比对软件. tophat工作分两步: 1.将reads用bowtie比对到参考基因组上. 2.将unmapped-reads打断成更小的fragment ...

  8. PHP类的变量与成员,及其继承、访问与重写要注意的问题

    PHP的类及其实例: <?php ?>  后期静态绑定:为了避免子类重写静态属性后,使用继承来的方法仍然方法父类的静态属性,PHP5.3增加了一个新的语法,后期静态绑定,使用static关 ...

  9. 线性代数:Ax=b的解

    n列的矩阵A,当且仅当向量b是列空间C(A)的一个向量时,Ax=b有解. C(A)的零空间是N(A),N(A)正交补是A的行空间C(T(A)), 依据上一章的结论,任何Rn向量可以表示为r+n,其中n ...

  10. ibecon后台运行

    程序被硬关闭后,只能执行这三个回调,而且必须写在appdelegate中,退出ibeacons信息区域时会有延时10秒左右,进入时无延时 - (void)locationManager:(CLLoca ...