二叉查找树迭代器
来源:互联网 发布:淘宝采集软件收费吗 编辑:程序博客网 时间:2024/05/21 19:49
设计实现一个带有下列属性的二叉查找树的迭代器:
- 元素按照递增的顺序被访问(比如中序遍历)
next()
和hasNext()
的询问操作要求均摊时间复杂度是O(1)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Example of iterate a tree:
* BSTIterator iterator = BSTIterator(root);
* while (iterator.hasNext()) {
* TreeNode * node = iterator.next();
* do something for node
*/
class BSTIterator {
public:
/*
* @param root: The root of binary tree.
*/
BSTIterator(TreeNode * root) {
// push all left nodes to stack
while (root != NULL) {
stack_.push(root);
root = root->left;
}
}
/*
* @return: True if there has next node, or false
*/
bool hasNext() {
// stack isn't null
return !stack_.empty();
}
/*
* @return: return next node
*/
TreeNode * next() {
// write your code here
TreeNode* tn = stack_.top();
stack_.pop();
// next is right child if not null
TreeNode* root = tn->right;
while (root != NULL) {
stack_.push(root);
root = root->left;
}
return tn;
}
private:
// stack to keep minimal nodes
stack<TreeNode*> stack_;
};
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Example of iterate a tree:
* BSTIterator iterator = BSTIterator(root);
* while (iterator.hasNext()) {
* TreeNode * node = iterator.next();
* do something for node
*/
class BSTIterator {
public:
/*
* @param root: The root of binary tree.
*/
BSTIterator(TreeNode * root) {
// push all left nodes to stack
while (root != NULL) {
stack_.push(root);
root = root->left;
}
}
/*
* @return: True if there has next node, or false
*/
bool hasNext() {
// stack isn't null
return !stack_.empty();
}
/*
* @return: return next node
*/
TreeNode * next() {
// write your code here
TreeNode* tn = stack_.top();
stack_.pop();
// next is right child if not null
TreeNode* root = tn->right;
while (root != NULL) {
stack_.push(root);
root = root->left;
}
return tn;
}
private:
// stack to keep minimal nodes
stack<TreeNode*> stack_;
};
阅读全文
0 0
- 二叉查找树迭代器
- 二叉查找树迭代器-LintCode
- LintCode_二叉查找树迭代器
- 二叉查找树迭代器
- lintcode(86)二叉查找树迭代器
- 二叉查找
- 查找--二叉查找树
- 【查找结构】二叉查找树
- 查找之二叉树查找
- 查找之二叉树查找
- 查找:二叉查找树总结
- 二叉树、二叉查找树
- 二叉树 & 二叉查找树
- 二叉排序和二叉查找
- 查找--遍历二叉树
- 二叉查找树
- 二叉查找树实现
- 二叉查找树
- JS之DOM对象
- values资源之color
- 针对SGX的缓存攻击(Cache Attack)调研
- 在ncverilog仿真条件设置中+nospecify ,+notimingcheck 和 +delay_mode_zero之间有什么区别
- ScrollView加载里面的数据出现下滑(可能是焦点问题)
- 二叉查找树迭代器
- 宣传一下自己的私人博客
- 多线程学习(一)
- Java Thread API
- Django框架学习笔记(22.CSRF原理简单介绍)
- 剑指Offer(三)从尾到头打印链表
- 51nod 1416 两点 -dfs
- 七牛云简单上传图片 展示
- vue入门