Binary Search Tree Iterator -- leetcode
2015-06-26 16:22
302 查看
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
Note:
run in average O(1) time and uses O(h) memory, where h is the height of the tree.
基本思路:
其实就是中序遍历的非递实现。
这next smallest意思就是,从小到大逐个返回。 第一次看到,竟然理解反了。还以为是从大到小逐个返回。
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.
基本思路:
其实就是中序遍历的非递实现。
这next smallest意思就是,从小到大逐个返回。 第一次看到,竟然理解反了。还以为是从大到小逐个返回。
/** * 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) { while (root) { s_.push(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !s_.empty(); } /** @return the next smallest number */ int next() { auto root = s_.top(); s_.pop(); auto ans = root->val; root = root->right; while (root) { s_.push(root); root = root->left; } return ans; } private: stack<TreeNode *> s_; }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
相关文章推荐
- Linux下如何进行FTP设置
- activity返回-通过手势退出当前activity
- Android 环境常见问题
- winform中treeview中节点选中的技巧
- 《GK101任意波发生器》升级固件发布(版本:1.0.2build851)
- 自定义View(1)--圆形图片、圆角图片的实现
- opencv学习笔记(二)
- Linux学习笔记(二)——主机规划及磁盘分区
- Js获取当前日期时间及格式化操作
- VS2013 环境的搭建
- hadoop学习
- C#中char[]与string之间的转换
- 登录拦截功能
- 健全的人生
- Linux中cp文件或目录时如何显示进度?
- typedef 函数指针用法
- ldap 身份验证的通用步骤
- 剑指offer 44-扑克牌的顺子
- 关于SpringMVC上传与导出excel问题
- 黑马程序员--C基础--各类读取函数