【leetcode 二叉树 C++】99. Recover Binary Search Tree

99. Recover Binary Search Tree

在这里插入图片描述

/**
 * 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> V;
    int cnt = 0;
    void getV(TreeNode* root) {
        if(!root) return ;
        getV(root->left);
        V.push_back(root->val);
        getV(root->right);
    }
    void recover(TreeNode* root) {
        if(!root) return ;
        recover(root->left);
        root->val = V[cnt++];
        recover(root->right);
    }
    void recoverTree(TreeNode* root) {
        getV(root);
        sort(V.begin(), V.end());
        recover(root);
    }
};
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页