思路:
在构造函数中就将中序遍历的结果存到队列中,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();
*/