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 ...
 
随机推荐
- 004-JVM指令集(指令码、助记符、功能描述)
			
一.JVM指令助记符 1)操作数栈 变量到操作数栈:iload,iload_,lload,lload_,fload,fload_,dload,dload_,aload,aload_ 操作数栈到变量:i ...
 - Oracle学习笔记—oracle体系架构及状态(nomount、mount和open)简介
			
oracle体系架构简介 先来简要了解一下Oracle数据库体系架构以便于后面深入理解,Oracle Server主要由实例(instance)和数据库(database)组成.实例(instance ...
 - BDC程序步骤
			
(1)记录屏幕操作: (2)产生相关程序和数据格式文件: (3)调整数据文件: (4)运行BDC产生的程序读取文件导入数据: (5)源代码分析: (6)用BDC 导入单据: 在理解ABAP 开发的sc ...
 - 【AWS】AWS云计算赋能数字化转型专题研讨会
			
点我查看详情 欢迎莅临
 - iOS  NSCoding 的学习 和 使用
			
起初接触的轻量级 物理存储 方式 是 plist 可以存储 系统级别的 字典 数组 但是不能存储自定义的对象类 那会 用自定义对象做存储的 需求也不大 主要 是 还没建立面向对象意识,会的也少. ...
 - Shell编程之Linux信号及信号跟踪
			
一.Linux信号 1.什么是信号? Linux信号是由一个整数构成的异步消息,它可以由某个进程发给其他进程,也可以在用户按下特定键发生某种异常事件时,由系统发给某个进程. 2.信号列表 [root@ ...
 - 封装一个既能遍历数组又能遍历对象的的forEach函数
			
function newforEach(obj,fn) { var key; if(obj instanceof Array){ obj.forEach(function(item,index){ f ...
 - ORA-01034和ORA-27101的错误
			
我本机安装的数据库版本是ORACLE 11G R2,用plsql连接时候,报ora-12514如下错误: 但是在cmd里用sqlplus连接已经创建的用户时候,报如下错误: ORA-01034 - O ...
 - PHP 面向对象及Mediawiki 框架分析(一)
			
此文是一JAVA哥大神写的,虽然他不懂PHP.我这人PHP半桶水,面向对象更是半桶水都没有,此文原本是为了让我理解MediaWiki的运行机制的,愣是用他的JAVA的面向对象知识,对Mediawiki ...
 - USB引脚及定义
			
USB 2.0 USB接口定义: USB引脚定义: 针脚 名称 说明 接线颜色 1 VCC +5V电压 红色 2 D- 数据线负极 白色 3 D+ 数据线正极 绿色 4 GND 接地 黑色 Min ...