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.
Solutions:
首先想到的要用中序遍历。
O(n) memory的算法:
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
this->root = root;
InOrderSearch(root);
if(root == NULL) {
return;
}
}
void InOrderSearch(TreeNode *t) {
if(t == NULL) {
return;
}
if(t->left != NULL) {
InOrderSearch(t->left);
}
Q.push(t);
if(t->right != NULL) {
InOrderSearch(t->right);
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !Q.empty();
}
/** @return the next smallest number */
int next() {
int ret=Q.front()->val;
Q.pop();
return ret;
}
private:
TreeNode *root;
queue<TreeNode*> Q;
};O(n)算法:
不用预先遍历所有节点。用一个栈保存即将要访问的节点,先入栈的后访问。每当访问一个节点时,将该节点出栈,并将其右孩子及其左链一并入队列。
从而可以实现动态更新栈内容,实现正确的中序访问次序。
本文介绍如何使用中序遍历来实现二叉搜索树(BST)的迭代器,重点阐述了如何通过栈结构在O(1)平均时间复杂度下完成操作,同时讨论了内存使用的优化。
&spm=1001.2101.3001.5002&articleId=45602167&d=1&t=3&u=0f6b5369349c4d2a99f8da75ac6e24a1)
507

被折叠的 条评论
为什么被折叠?



