leetcode-99-树题-恢复二叉搜索树 发表于 2020-03-24 | 分类于 数据结构与算法 题目 解法1234567891011121314151617181920212223242526272829303132333435363738394041/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void recoverTree(TreeNode* root) { vector<int> result; inOrder(root, result); sort(result.begin(), result.end()); recover(root, result); } void inOrder(TreeNode* root,vector<int>& vecResult){ if(root == nullptr){ return; } inOrder(root->left,vecResult); vecResult.push_back(root->val); inOrder(root->right,vecResult); } void recover(TreeNode* root,vector<int>& rec){ if(root ==nullptr){ return; } recover(root->left,rec); if(root->val == rec[0]){ rec.erase(rec.begin()); }else{ root->val = rec[0]; rec.erase(rec.begin()); }; recover(root->right,rec); }};