/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
const int N=1010;
class Solution {
public:
int a[1010],idx=0;
int cnt=0;//记录dfs遍历结点是第几个
void getList(TreeNode* u){
if(u==nullptr) return;
getList(u->left);
a[idx++]=u->val;
getList(u->right);
}
void changeVal(TreeNode* u){
if(u==nullptr) return;
changeVal(u->left);
if(u->val!=a[cnt]) u->val=a[cnt];
cnt++;
changeVal(u->right);
}
//中序遍历一次得到序列,sort然后重新中序修改
TreeNode* recoverTree(TreeNode* root) {
memset(a,0,sizeof a);
getList(root);
sort(a,a+idx);
changeVal(root);
return root;
}
};