LeetCode Binary Search Tree Iterator
2015-09-12 22:04
225 查看
思路:
在构造函数中就将中序遍历的结果存到队列中,hasNext()与next()依次取队列中的元素。
改进:不断构造中序序列而不是一次构造。
在构造函数中就将中序遍历的结果存到队列中,hasNext()与next()依次取队列中的元素。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { private: queue<int> minq; stack<TreeNode*> s; map<TreeNode*, bool> m; public: BSTIterator(TreeNode *root) { //inoder traverse TreeNode *p = root; while(p != NULL || !s.empty()) { if(p != NULL) { s.push(p); p = p->left; }else { p = s.top(); s.pop(); minq.push(p->val); p = p->right; } } } /** @return whether we have a next smallest number */ bool hasNext() { return !minq.empty(); } /** @return the next smallest number */ int next() { int front = minq.front(); minq.pop(); return front; } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
改进:不断构造中序序列而不是一次构造。
/** * 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*> 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 *top = s.top(); int val = top->val; s.pop(); top = top ->right; while(top) { s.push(top); top = top->left; } return val; } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
相关文章推荐
- HDU 1159 【基础DP 最长公共子序列】
- base64编解码方法
- C++_队列的两种实现方法
- Bootstrap标签Tabs
- sudo用户管理
- 在Linux 系统 Latex安装 使用入门教程
- CCF 2013年12月 3题
- 若操作系统没有加载网卡驱动,网卡虽然在系统设备树上,但网卡接口创建不了,那网卡实际能不能接收到数据?
- 《head first python》——定制数据对象
- java设计模式第7弹--观察者模式
- easyui之datagrid的使用
- 使用IDEA编译spark 1.5并运行example的代码
- CCF 2015年3月 3题
- Eclipse下安装keil插件和导入keil工程教程
- 寻找Coder
- iOS开发脚踏实地学习day07-美团
- java.sql.SQLException: Value'0000-00-00'异常解决
- 网卡的MAC和PHY间的关系?
- tp实例化一个基础功能(供应商)
- C语言的中断信号