LintCode_二叉查找树迭代器
来源:互联网 发布:淘宝外贸的衣服能买吗 编辑:程序博客网 时间:2024/06/04 19:42
设计实现一个带有下列属性的二叉查找树的迭代器:
- 元素按照递增的顺序被访问(比如中序遍历)
next()
和hasNext()
的询问操作要求均摊时间复杂度是O(1)
样例
对于下列二叉查找树,使用迭代器进行中序遍历的结果为 [1, 6, 10, 11, 12]
10 / \1 11 \ \ 6 12
思路就是引入一个辅助栈。在遍历的过程中利用辅助栈逆序地记录和保存沿途经过的各个节点,以便确定自底而上各段遍历子序列最终在宏观上的拼接次序。
/** * 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) { curr=nullptr; //持续深入左子树 while(root) { S.push(root); root=root->left; } } //@return: True if there has next node, or false bool hasNext() { return (S.empty()?false:true); } //@return: return next node TreeNode* next() { if (S.empty()) { return NULL; } TreeNode *top = S.top(); S.pop(); //先把下一个节点拿出来 if (top->right) //如果该节点有右子树,则还要处理子树的点 { TreeNode *cur = top->right; while (cur) { S.push(cur); //推入栈中去,此时S.front就是下一个结点 cur = cur->left; } } return top; }private: TreeNode* curr; stack<TreeNode*> S;};
阅读全文
0 0
- LintCode_二叉查找树迭代器
- LintCode_在二叉查找树中插入节点
- lintCode_二分查找
- LintCode_字符串查找
- LintCode_二叉查找树中搜索区间_简单的递归实现
- 二叉查找树迭代器
- 二叉查找树迭代器-LintCode
- 二叉查找树迭代器
- lintcode(86)二叉查找树迭代器
- LintCode_中位数
- 二叉查找
- 查找--二叉查找树
- 【查找结构】二叉查找树
- 查找之二叉树查找
- 查找之二叉树查找
- 查找:二叉查找树总结
- 二叉树、二叉查找树
- 二叉树 & 二叉查找树
- 剑指Offer—28—数组中出现次数超过一半的数字
- 润乾报表如何配置/部署多个lmd文件
- Leetcode 122. Best Time to Buy and Sell Stock II
- html 学习 第一天
- USB驱动--概念
- LintCode_二叉查找树迭代器
- Vue列表过渡
- C++实验二 控制结构和函数 打印温度柱状图 2.2 处理零下温度
- JAVA学习50_java 主类的main方法调用其他方法
- php正则
- 20170823-BIN
- 宋宝华:Linux的任督二脉——进程调度和内存管理
- 1.fork产生新进程学习
- eclipse出错信息