思路:
在构造函数中就将中序遍历的结果存到队列中,hasNext()与next()依次取队列中的元素。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
queue<int> minq;
stack<TreeNode*> s;
map<TreeNode*, bool> m;
public:
BSTIterator(TreeNode *root) {
//inoder traverse
TreeNode *p = root;
while(p != NULL || !s.empty()) {
if(p != NULL) {
s.push(p);
p = p->left;
}else {
p = s.top();
s.pop();
minq.push(p->val);
p = p->right;
}
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !minq.empty();
}
/** @return the next smallest number */
int next() {
int front = minq.front();
minq.pop();
return front;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
改进:不断构造中序序列而不是一次构造。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
private:
stack<TreeNode*> s;
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() {
TreeNode *top = s.top();
int val = top->val;
s.pop();
top = top ->right;
while(top) {
s.push(top);
top = top->left;
}
return val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
本文详细介绍了如何优化中序遍历来构造二叉搜索树迭代器,通过栈和队列实现高效的节点访问顺序。改进了构造方式,避免了一次性构建整个中序序列,提高了内存效率和性能。
3530

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



