力扣第99题恢复二叉搜索树

题目

在这里插入图片描述
在这里插入图片描述

题解

二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。二叉搜索树作为一种经典的数据结构,它既有链表的快速插入与删除操作的特点,又有数组快速查找的优势;所以应用十分广泛,例如在文件系统和数据库系统一般会采用这种数据结构进行高效率的排序与检索操作。(开源:百度百科)
简而言之,就是左子树的值一定要比根节点小,右子树的值一定要比根节点大。
通过探索发现,如果将二叉查找树进行中序排列,那么生成的列表将是升序排列,我们可以依据这个解题。

注:三种排列方式

代码段

本次解题采用了最为老实的办法,一步步,先遍历列表然后去比较大小,代码参考了力扣用户:ni8fun的讲解后自己敲写

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int lenth(struct TreeNode*root){
    if(!root) return 0;
    return lenth(root->left)+lenth(root->right)+1;
}

void list(struct TreeNode* root,int *arr,int *b){
    if(!root) return ;
    
    list(root->left,arr,b);
    arr[(*b)++] = root->val;
    list(root->right,arr,b);

    return ;
}

bool replace(struct TreeNode* root ,int x,int y,int count){
    if(!root) return false;

    if(root->val == x){
        root->val = y;
        if(count==1) return true;
        else count ++;
    }
    else { 
        if(root->val == y){
            root->val = x;
            if(count==1) return true;
            else count ++;
        }
         
    }

    if(replace(root->left, x, y, count)) return true;
    if(replace(root->right, x, y, count)) return true;

    return false;

}
void recoverTree(struct TreeNode* root){
    if(!root || (!root->left && !root->right));
    int *arr = (int*)malloc(lenth(root)*sizeof(int));
    int num = 0;
    int *b = #
    //中序便利
    list(root,arr,b);

    //排序
    int x = 0;
    int y = 0;
    for (int i =0;i<*b-1;i++){
        if(arr[i]>arr[i+1]){
            y = arr[i+1];
            if (x == 0) x = arr[i];
        }
    }

    //替换
    replace(root,x,y,0);
    return ;

}

总结

这个题其实记住了二叉搜索树的中序排列是升序排列就有了思路,剩下的全靠实操,长路慢慢,自己太菜

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Battle_Cry#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值