leetcode99. 恢复二叉搜索树

分析

思路一

中序遍历将二叉树的元素存入数组中,然后将数组排序,再将数组的中重新恢复到二叉树中。

/**
 * 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) {}
 * };
 */
class Solution {
public:
    vector<int> vals;
    void inorder(TreeNode* node){
        if(node->left)inorder(node->left);
        vals.push_back(node->val);
        if(node->right)inorder(node->right);
    }
    void inorder2(TreeNode* &node){
        if(node->left)inorder2(node->left);
        node->val=vals[0];
        vals.erase(vals.begin());
        if(node->right)inorder2(node->right);
    }
    void recoverTree(TreeNode* root) {
        inorder(root);
        sort(vals.begin(),vals.end());
        inorder2(root);
        
    }
};