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.

采用中序遍历将节点压入栈中,由于要求存储空间为O(h),因此不能在一开始将所有节点全部压入,只是压入最左边一列。当取出一个节点时,压入其右子节点的所有左节点。

 /**
* 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;
int minres;
public:
BSTIterator(TreeNode *root) {
while(root)
{
stk.push(root);
root=root->left;
}
} /** @return whether we have a next smallest number */
bool hasNext() {
if(stk.empty())
return false;
TreeNode* top;
top=stk.top();
minres=top->val;
stk.pop();
TreeNode* cur=top->right;
if(cur)
{
stk.push(cur);
cur=cur->left;
while(cur)
{
stk.push(cur);
cur=cur->left;
}
}
return true;
} /** @return the next smallest number */
int next() {
return minres;
}
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/

最新文章

  1. WSDL项目---处理消息
  2. reactjs
  3. Robot Framework--11 RF结合Jenkins
  4. (转)数据库获得当前时间getdate()
  5. asp.net Linq 实现分组查询
  6. [SAP] 外部系统调用SAP web service用户验证的简单方法
  7. 认识ExtJS(04)--常见Web框架的ExtJS改造
  8. Sematic库系列一
  9. FFT初解(转)
  10. python--对函数的理解
  11. Unity获取安卓手机运营商,电量,wifi信号强度,本地Toast,获取已安装apk,调用第三方应用,强制自动重启本应用
  12. rpm 相关问题
  13. 笔记:Hibernate DML
  14. linux 服务器网络有关的内核参数
  15. 001-为什么Java能这么流行
  16. appium 版本更新后的方法变化更新收集 ---持续更新
  17. Python 14 Html 基础
  18. redis make编译失败的原因
  19. NDK/JNI学习--环境搭建
  20. Go 实现异常处理机制

热门文章

  1. Android项目实战(四):ViewPager切换动画(3.0版本以上有效果)
  2. 部分博文目录索引(C语言+算法)
  3. 【读书笔记】iOS-写代码注意事项
  4. UIScrollView常见属性
  5. iOS 准确计算某个时间点距现在的时间差的代码 如&quot;几分钟,几小时,几秒之前&quot; ,
  6. Matlab2014下载和破解方法,以及Matlab很好的学习网站
  7. animation of android (2)
  8. windows 和 linux ssh互连
  9. sublime生产力提升利器
  10. 最近学习linux常用命令。