leetCode(24):Binary Search Tree Iterator
2024-09-08 08:28:48
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();
*/
最新文章
- cv_prj2
- iOS Notification 的使用
- 13年7月memory point
- ios二维码扫描插件,适配当前主流扫描软件,自定义扫描界面。
- 学习使用Free RTOS ,移植最新的STM32 v3.5固件库
- 编写JQuery插件-2
- UEditor编辑器和php简单的实现socket通信
- Docker镜像构建的两种方式
- VS Code保存使用项目Eslint规则格式化代码
- pycharm断点应用
- 关于vue的基础概念
- 使用xshell+xmanager+pycharm搭建pytorch远程调试开发环境
- win10和ubuntu16.04双系统Geom Error
- 安装gcc4.8.5
- Windows剪贴板操作简单小例
- ScrambleString, 爬行字符串,动态规划
- 一个简单的仿 Launcher 应用
- CSS3实现多列纵向滚动
- django自带的orm之查询
- HTTP/2之旅 (翻译)
热门文章
- 洛谷—— P1262 间谍网络
- N - 畅通工程再续
- 日志log配置理解
- iterator遍历list理解
- 初探swift语言的学习笔记十(block)
- [Phonegap+Sencha Touch] 移动开发19 某些安卓手机上弹出消息框 点击后不消失的解决的方法
- ChrisRenke/DrawerArrowDrawable源代码解析
- How to remove focus without setting focus to another control?
- php常用知识集锦
- oracle init.ora常用配置详解