题目:

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

代码:

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
vector<TreeNode*> list;
int index;
public:
BSTIterator(TreeNode *root) {
BSTIterator::treeToList(root, this->list);
this->index = ;
} static void treeToList(TreeNode* root, vector<TreeNode*>& ret)
{
if ( !root ) return;
BSTIterator::treeToList(root->left, ret);
ret.push_back(root);
BSTIterator::treeToList(root->right, ret);
} /** @return whether we have a next smallest number */
bool hasNext() {
return index < this->list.size();
} /** @return the next smallest number */
int next() {
return list[index++]->val;
}
}; /**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/

tips:

这个题目的核心就是在于中序遍历 把BST转化成vector,这样可以实现题目的要求。

最新文章

  1. 5 HTML&amp;JS等前端知识系列之jquery基础
  2. git+github上传与管理
  3. WebAPi添加常用扩展方法及思维发散
  4. git之remote branch controller(远程分支控制)
  5. RFC(请求注解)--各种协议-标准
  6. 【hdu5973】高精度威佐夫博弈
  7. swift项目实战FoodPin目录
  8. RecyclerView的使用方法
  9. mssql 常用SQL语句或函数
  10. 让所有浏览器包括IE6即支持最大宽度又支持最小宽度。
  11. rc.local自启动学习(转)
  12. linux 使用kill命令杀死进程的几个办法
  13. JavaScript高级程序设计30.pdf
  14. 关于java中for和foreach循环
  15. JQuery日历插件My97DatePicker日期范围限制
  16. ActiveMQ in Action(4) - Security
  17. Alpha冲刺Day4
  18. Linux(DeepInOS) 下 mysql 的安装与基本配置
  19. spring boot junit controller
  20. Linux服务器下安装vmware虚拟机

热门文章

  1. MySQL入门很简单: 14MySQL日志
  2. poj 2112 Optimal Milking 奶牛
  3. 课程设计__C++初步,C++对C的扩充
  4. caffe RandomOrderChannels
  5. django.template.exceptions.TemplateSyntaxError: &#39;article_tags&#39; is not a registered tag library.
  6. LeetCode94. Binary Tree Inorder Traversal
  7. 【赛时总结】 ◇赛时&#183;I◇ AtCoder ARC-098
  8. SAP BI 常用TCODE
  9. CSS之美化页面
  10. 云计算之KVM虚拟化实战