173. Binary Search Tree Iterator
来源:互联网 发布:淘宝云客服工资怎么算 编辑:程序博客网 时间:2024/06/13 21:36
mplement 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: queue<int> minq; BSTIterator(TreeNode *root) { stack<TreeNode*> st; while (root != NULL || !st.empty()) { if (root != NULL) { st.push(root); root = root->left; } else { root = st.top(); minq.push(root->val); root = root->right; } } } /** @return whether we have a next smallest number */ bool hasNext() { return !minq.empty(); } /** @return the next smallest number */ int next() { int minval = minq.front(); minq.pop(); return minval; }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
时间上是绝对的O(1),空间上确实O(N).
不知道如果做到时间O(1)还能空间O(logN).
给出时间空间都是O(logN)解法。
class BSTIterator {public: stack<TreeNode*> st; BSTIterator(TreeNode *root) { pushleft(root); } void pushleft(TreeNode *root) { while (root != NULL) { st.push(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !st.empty(); } /** @return the next smallest number */ int next() { TreeNode* temp = st.top(); st.pop(); pushleft(temp->right); return temp->val; }};
阅读全文
1 0
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator**
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- 173. Binary Search Tree Iterator
- python -- K最近邻算法
- SubTool 电影字幕下载程序
- 通配符的继承关系
- 在线报表设计实战系列 – ⑦制作图表类报表
- 图片数据集太少?看我七十二变,Keras Image Data Augmentation 各参数详解
- 173. Binary Search Tree Iterator
- AES加密解密
- ios入门:点击屏幕其他区域,隐藏软键盘
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- Maven下载、安装和配置(二)
- 1.字符串概述-String
- aspectj简介
- linux sed命令实现替换和打印
- 通用mapper报错 无法获取实体类XXX对应的表名!