首页 > 其他分享 >leetcode 99. 恢复二叉搜索树

leetcode 99. 恢复二叉搜索树

时间:2023-02-21 19:04:00浏览次数:43  
标签:rt zhongxu val zhong paizhong 二叉 99 dizhi leetcode

中序遍历,弄在数组里面,再弄个数组复制一份排好序
比较哪里错了,换回来
中序遍历的时候用map存一下数字的地址(默认没有重复元素)

class Solution {
public:
    vector<int> zhong;
    map<int,TreeNode*> dizhi;
    void recoverTree(TreeNode* root) {
        if( root == nullptr ){
            return;
        }
        zhongxu(root);
        vector<int>paizhong(zhong);
        sort(paizhong.begin(),paizhong.end());
        //debug( zhong.size() )
        for(int i=0;i<zhong.size();i++){
            if(zhong[i] != paizhong[i]){
                swap( dizhi[ zhong[i] ]->val,dizhi[ paizhong[i] ]->val);
                //cout<<"1"<<endl;
                break;
            }

        }
    }
    void zhongxu( TreeNode * rt ){
        if( rt!= nullptr ){
            zhongxu( rt->left );
            zhong.push_back(rt->val);
            dizhi[rt->val] = rt;
            zhongxu( rt->right );
        }
    }
};

leetcode 99. 恢复二叉搜索树_重复元素

标签:rt,zhongxu,val,zhong,paizhong,二叉,99,dizhi,leetcode
From: https://blog.51cto.com/liyunhao/6077024

相关文章