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 {
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();
*/

最新文章

  1. cv_prj2
  2. iOS Notification 的使用
  3. 13年7月memory point
  4. ios二维码扫描插件,适配当前主流扫描软件,自定义扫描界面。
  5. 学习使用Free RTOS ,移植最新的STM32 v3.5固件库
  6. 编写JQuery插件-2
  7. UEditor编辑器和php简单的实现socket通信
  8. Docker镜像构建的两种方式
  9. VS Code保存使用项目Eslint规则格式化代码
  10. pycharm断点应用
  11. 关于vue的基础概念
  12. 使用xshell+xmanager+pycharm搭建pytorch远程调试开发环境
  13. win10和ubuntu16.04双系统Geom Error
  14. 安装gcc4.8.5
  15. Windows剪贴板操作简单小例
  16. ScrambleString, 爬行字符串,动态规划
  17. 一个简单的仿 Launcher 应用
  18. CSS3实现多列纵向滚动
  19. django自带的orm之查询
  20. HTTP/2之旅 (翻译)

热门文章

  1. 洛谷—— P1262 间谍网络
  2. N - 畅通工程再续
  3. 日志log配置理解
  4. iterator遍历list理解
  5. 初探swift语言的学习笔记十(block)
  6. [Phonegap+Sencha Touch] 移动开发19 某些安卓手机上弹出消息框 点击后不消失的解决的方法
  7. ChrisRenke/DrawerArrowDrawable源代码解析
  8. How to remove focus without setting focus to another control?
  9. php常用知识集锦
  10. oracle init.ora常用配置详解