solution using O(n) space,二叉树中序遍历
class Solution {
public:
void recoverTree(TreeNode *root) {
if(root==NULL)
return;
TreeNode *first=NULL,*second=NULL,*last=NULL;
stack<TreeNode*> stack;
while(root){
stack.push(root);
root=root->left;
}
while(!stack.empty()){
TreeNode *p=stack.top();
stack.pop();
if(last==NULL)
last=p;
else if(p->val<last->val){
if(first==NULL){
first=last;
second=p;
}
else{
second=p;
break;
}
}
last=p;
p=p->right;
while(p){
stack.push(p);
p=p->left;
}
}
if(first){
int temp=first->val;
first->val=second->val;
second->val=temp;
}
}
};
constant space solution,直接用递归就不用花n的空间了
class Solution {
TreeNode *first,*second,*last;
public:
void recover(TreeNode *root){
if(root==NULL)
return;
recover(root->left);
if(last!=NULL&&last->val>root->val){
if(first==NULL){
first=last;
second=root;
}
else
second=root;
}
last=root;
recover(root->right);
}
void recoverTree(TreeNode *root) {
if(root==NULL)
return;
first=second=last=NULL;
recover(root);
if(first){
first->val^=second->val;
second->val^=first->val;
first->val^=second->val;
}
}
};