class Solution {
public:
void recoverTree(TreeNode* root) {
if(root==NULL) return;
vector<int> num;
vector<TreeNode*> tree;
inorder(root,num,tree);
vector<int> sorted = num;
sort(sorted.begin(),sorted.end());
int id1=-1,id2=-1;
for(int i=0;i<num.size();i++){
if(num[i]!=sorted[i]&& id1==-1) id1=i;
if(num[i]!=sorted[i]&& id1!=-1) id2=i;
}
int tmp = tree[id1]->val;
tree[id1]->val=tree[id2]->val;
tree[id2]->val =tmp;
return;
}
void inorder(TreeNode * root,vector<int> & num,vector<TreeNode*>& tree){
if(root==NULL) return;
inorder(root->left,num,tree);
num.push_back(root->val);
tree.push_back(root);
inorder(root->right,num,tree);
return;
}
};
得到树的中序遍历序列,然后排序,相同位置元素不同的那两个就是错误的节点,交换值即可。