class BSTIterator {
public:
stack<TreeNode* >s;
BSTIterator(TreeNode* root) {
cal(root);
}
void cal(TreeNode* root){//从root一直往左儿子,将这一路都放到栈里
while(root) s.push(root),root=root->left;
}
int next() {
TreeNode *ans=s.top();s.pop();
if(ans->right) cal(ans->right);//要弹出ans了,将从ans.right一直往左儿子,这一路都放到栈里
return ans->val;
}
bool hasNext() {
return s.size()>0;
}
};
题目要求next() 和 hasNext() 操作的时间复杂度是 O(1),我上一种方法,next()好像是最大o(h)把。
这个方法更不是了。
这里每次next()函数,一定是while(root),不能是if(root),因为if(root),if(root)的话,每次可能root->left,然后添加完🔗,就直接if结束了,然后就没有然后了,,
class BSTIterator {
public:
TreeNode *root;
BSTIterator(TreeNode* root) {
this->root=root;
}
int next() {
while(root){
if(root->left){
TreeNode *predessor=root->left;
while(predessor->right!=NULL&&predessor->right!=root) predessor=predessor->right;
if(predessor->right==NULL){
predessor->right=root;
root=root->left;
}else{
predessor->right=NULL;
TreeNode *tmp=root;
root=root->right;
return tmp->val;
}
}else{
TreeNode *tmp=root;
root=root->right;
return tmp->val;
}
}
return -1;
}
bool hasNext() {
return root!=NULL;
}
};