leetCode(24):Binary Search Tree Iterator
2015-06-23 11:50
239 查看
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
run in average O(1) time and uses O(h) memory, where h is the height of the tree.
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 { public: BSTIterator(TreeNode *root) { i=0; if(NULL==root) { length=0; } else { stack<TreeNode*> nodes; TreeNode* cur=root; while(!nodes.empty() || cur) { while(cur) { nodes.push(cur); cur=cur->left; } cur=nodes.top(); nodesValue.push_back(cur->val); nodes.pop(); cur=cur->right; } length=nodesValue.size(); } } /** @return whether we have a next smallest number */ bool hasNext() { if(i<length) return true; return false; } /** @return the next smallest number */ int next() { return nodesValue[i++]; } private: vector<int> nodesValue; int i; int length; }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
相关文章推荐
- 完全合并C++面试题
- leetCode(24):Binary Search Tree Iterator 分类: leetCode 2015-06-23 11:50 192人阅读 评论(0) 收藏
- Kettle数据固化流程
- syn flood
- <context:component-scan>使用说明
- 寄存器描述中使用的缩写列表
- 删除进程占用文件
- 面向物联感知终端的Java网络编程 (一)
- 关于hard code
- Android app 开发套路
- STM32通过SIM800L向yeelink端上传数据
- 项目管理系统 SQL2005数据库查询CPU100%问题研究
- Oracle监听器日志配置与管理
- 计算机通信理论——问题问答
- 华为OJ----洞穴逃生
- Android省市区三级联动滚轮选择(真实项目中提取出来的组件)
- 日志框架实现实时修改,实时生效,具体框架思路(6)
- 控制器基类
- 为什么项目屡屡延期 - 占空比对工期的显著影响
- Oracle之序列