173.二叉搜索树迭代器
题目描述
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
思路
控制中序遍历的进程,不要让它一次性结束,如果用解法一递归的方法去遍历那就很难控制了,所以自然而然的会想到用栈模拟递归的过程。
把 stack 和 cur 作为成员变量,然后每次调用 next 就执行一次 while 循环,并且要记录当前值,结束掉本次循环
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
TreeNode* cur = NULL;
stack<TreeNode*> treeStack;
BSTIterator(TreeNode* root) {
cur = root;
}
/** @return the next smallest number */
int next() {
int res = -1;
while(cur != NULL || !treeStack.empty()){
while(cur != NULL){
treeStack.push(cur);
cur = cur->left;
}
cur = treeStack.top();
treeStack.pop();
res = cur->val;
cur = cur->right;
break;
}
return res;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return cur != NULL || !treeStack.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
复杂度分析
时间复杂度的话,对于 next 方法,大多数时候是 O(1),但最坏情况因为最里边的 while 循环,其实有可能达到 O(n)。但如果算均摊时间复杂度的话,其实还是 O(1),因为每个节点最多也就经过两次就出栈了。
空间复杂度,这里只需要消耗栈的空间,也就是 O(h)。