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. Eclipse中执行maven命令(转载)

    转载自:http://blog.csdn.net/u011939453/article/details/43017865 1.如下图,右击需要执行maven命令的工程,选择"Debug As ...

  2. 方阵行列式并行化计算(OpenMP,MPI),并计算加速比

    00][100].在创建方阵时,方阵的阶数N(N<100)由外部输入.然后用两层"for循环"来给方阵 p左上角 N×N个位置赋值.具体实现如下: /* * 定义矩阵阶数N ...

  3. 剑指offer 面试9题

    面试9题: 题目:用两个栈实现队列 题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 解题思路:有两个栈stackA,stackB,A为入栈,B为出栈的. ...

  4. Unicode与UTF-8/UTF-16/UTF-32的区别

    Unicode的最初目标,是用1个16位的编码来为超过65000字符提供映射.但这还不够,它不能覆盖全部历史上的文字,也不能解决传输的问题 (implantation head-ache's),尤其在 ...

  5. requestAnimationFrame 的实验性实践

    记得当 requestAnimationFrame 出现时我立马就石更了,就跟初次玩耍 transition 时一样,欣喜若狂... 然后,然后特么的就懵逼了,这明明就是口挖不通的深井呀(如果是我傻, ...

  6. MongoDB快速入门(九)- 投影

    MongoDB投影 mongodb投影意义是只选择需要的数据,而不是选择整个一个文档的数据.如果一个文档有5个字段,只需要显示3个,只从中选择3个字段. MongoDB的find()方法,解释了Mon ...

  7. freopen重定向输入

    #include <bits\stdc++.h> using namespace std; int main() { freopen("C:\\Users\\dcf\\Deskt ...

  8. CDN技术介绍

    CDN技术介绍 一.CDN概述 1.1 CDN定义 CDN即Content Delivery Network (内容分发网络).CDN是建立在现有IP网络基础结构之上的一种增值网络.是在应用层部署的一 ...

  9. html文件转换成pdf和word

    1.html文件转成pdf 采用jar包有itext-asian.jar.itextpdf-5.5.5.jar.itext-pdfa-5.5.5.jar.itext-xtra-5.5.5.jar,为了 ...

  10. Variation calling and annotation

    Resequencing 302 wild and cultivated accessions identifies genes related to domestication and improv ...