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.

思路:

说白了,就是把中序遍历拆成几个部分写。

我的代码:

class BSTIterator {
public:
BSTIterator(TreeNode *root) {
pCur = root;
while(pCur != NULL)
{
v.push_back(pCur);
pCur = pCur->left;
}
} /** @return whether we have a next smallest number */
bool hasNext() {
return (!v.empty() || NULL != pCur);
} /** @return the next smallest number */
int next() {
int num;
TreeNode * tmp = v.back();
v.pop_back();
num = tmp->val;
pCur = tmp->right;
while(pCur != NULL)
{
v.push_back(pCur);
pCur = pCur->left;
}
return num;
}
private:
vector<TreeNode *> v;
TreeNode * pCur;
};

大神更精简的代码: 经验,把相同功能的代码放在一起可以简化代码。

public class BSTIterator {

        Stack<TreeNode> stack =  null ;
TreeNode current = null ; public BSTIterator(TreeNode root) {
current = root;
stack = new Stack<> ();
} /** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty() || current != null;
} /** @return the next smallest number */
public int next() {
while (current != null) {
stack.push(current);
current = current.left ;
}
TreeNode t = stack.pop() ;
current = t.right ;
return t.val ;
}
}

最新文章

  1. Codeigniter的Redis使用
  2. 深入java集合系列文章
  3. NPOI 2.0 创建Excel文件
  4. Hibernate(六)__对象的三种状态
  5. linux中shell截取字符串方法总结
  6. NHibernate实战详解(二)映射配置与应用
  7. hdu 1851 尼姆+巴什博弈
  8. realestate.cei.gov.cn
  9. 如何将 Cortana 与 Windows Phone 8.1 应用集成 ( Voice command - Natural language recognition )
  10. R12.2.0 buildStage 运行结果
  11. invalid byte 1 of 1-byte UTF-8 sequence
  12. JS控制图片拖动 放大 缩小 旋转 支持滚轮放大缩小 IE有效
  13. $(&#39;li&#39;,&#39;div&#39;) $(&#39;div li&#39;) $(&#39;div li&#39;)
  14. java 技术体系
  15. 这次GDC China 2015的总结与关卡设计教程的梳理
  16. junit4笔记
  17. Attach()函数和Detach()函数的作用
  18. 基于NHibernate二级缓存的MongoDB组件
  19. LinkedHashSet的概述和使用
  20. pip命令

热门文章

  1. 黑客攻防技术宝典Web实战篇(三)web攻击方式总结
  2. 2015年12月01日 GitHub入门学习(二)手把手教你Git安装
  3. lustre文件系统部署流程
  4. compareTo(String str)与compareToIgnoreCase(String str)
  5. 学C++50条建议
  6. 几个Jquery对话框插件
  7. iOS开发——高级篇——地图 MapKit
  8. iOS开发——高级篇——iOS键盘的相关设置(UITextfield)
  9. windows7 + cocos2d-x 3.2 +vs2012 速度真的很慢
  10. event相关