中序遍历,保存节点和节点值,重新赋值
https://www.cnblogs.com/grandyang/p/4298069.html
O(1)复杂度用Mirror遍历
class Solution {
public:
void recoverTree(TreeNode *root) {
vector<TreeNode*>list;
vector<int>vals;
inorder(root,list,vals);
sort(vals.begin(),vals.end());
for(int i=0;i<list.size();i++)
list[i]->val=vals[i];
}
void inorder(TreeNode*root,vector<TreeNode*>&list,vector<int>&vals)
{
if(!root)return;
inorder(root->left,list,vals);
list.push_back(root),vals.push_back(root->val);
inorder(root->right,list,vals);
}
};
网友评论