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.

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
vector<int> v;
int pos;
public:
BSTIterator(TreeNode *root) {
pos = ;
stack<TreeNode*> s;
TreeNode *p = root, *pre = NULL;
while(p || !s.empty())
{
while(p)
{
s.push(p);
p = p->left;
}
if(!s.empty())
{
p = s.top();
s.pop();
v.push_back(p->val);
p = p->right;
}
}
} /** @return whether we have a next smallest number */
bool hasNext() {
return pos < v.size();
} /** @return the next smallest number */
int next() {
return v[pos++];
}
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/

最新文章

  1. 跳出IFrame几种方式
  2. SQL2005中的事务与锁定(七) - 转载
  3. Linux系统软件
  4. java核心知识点学习----多线程间的数据共享的几种实现方式比较
  5. Python序列的切片操作与技巧
  6. 技术分享:WIFI钓鱼的入门姿势
  7. hd1496----&gt;这道题是水水的数论吗?
  8. VS2012配置Lua环境
  9. asp图片化电话号码,避免蜘蛛之类爬走用户隐私
  10. poj 3259Wormholes (spfa最短路径)
  11. junit测试时,出现java.lang.IllegalStateException: Failed to load ApplicationContext
  12. 使用npm install时一直报错-4048 operation not permitted
  13. 【Java多线程】线程状态、线程池状态
  14. SNF快速开发平台3.0之-界面个性化配置+10种皮肤+7种菜单-Asp.net+MVC4.0+WebAPI+EasyUI+Knockout
  15. PHP开启伪静态(AppServ服务器)
  16. 牛客OI周赛4-提高组 B 最后的晚餐(dinner)
  17. CrystalReports2007安装包
  18. 基于centos6.5 hadoop 伪分布式安装
  19. 第三百六十五节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)的基本查询
  20. POJ-1959 Darts

热门文章

  1. Allocation Sinking Optimization
  2. mysql线上负载高怎么排查
  3. Network---3694poj(桥与LCA)
  4. Python开发【模块】:邮件
  5. hive引入jar包--HIVE.AUX.JARS.PATH和hive.aux.jars.path
  6. 爬虫之BeautifulSoup
  7. day14(编码实战-用户登录注册)
  8. DIY自己的GIS程序(2)——局部刷新
  9. Debian更新软件源提示There is no public key available for the following key IDs的解决方法
  10. HDU5183 hash 表