99.恢复二叉搜索树(Recover Binary Search Tree)


/*
Sologala @github https://github.com/Sologala/LeetCode.git
LeetCode 99._恢复二叉搜索树
*/

二叉搜索树中的两个节点被错误地交换。

请在不改变其结构的情况下,恢复这棵树。

思路

​ 中序序列(同时保存指针)搞到手,然后排序一下得到正确的序列,将中序得到的序列 与排好序的比对,找出两个错误位置的节点,交换两个指针的值。

示例 1:

输入: [1,3,null,null,2]

   1
  /
 3
  \
   2

输出: [3,1,null,null,2]

   3
  /
 1
  \
   2

执行用时: 28 ms, 在Recover Binary Search Tree的C++提交中击败了99.21%的用户

ac_code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
bool cmp(const TreeNode* a,const TreeNode*b){
        return a->val<b->val;
    }
class Solution {
    vector<TreeNode*> s;
    vector<TreeNode*> s1;
public:
    void recoverTree(TreeNode* r) {
       	inorder(r);
        s1=s;
        sort(s1.begin(),s1.end(),cmp);
        TreeNode* p[2];
        int cnt =0;
        for(int i=0;i<s.size()&&cnt<2;i++){
            if(s[i]!=s1[i]){
                p[cnt++]=s[i];
            }
        }
        swap(p[0],p[1]);
    }
    void swap(TreeNode* &a ,TreeNode* &b){
         int temp =a->val;
         a->val =b->val;
         b->val =temp;
	}
    void inorder(TreeNode* r){
        if(!r)return;
        inorder(r->left);
        s.push_back(r);
        inorder(r->right);
    }
    
};

猜你喜欢

转载自blog.csdn.net/sologala/article/details/86631275