代码随想录第二十天(一刷&&C语言)|修剪二叉搜索树&&将有序数组转换为二叉搜索树&&把二叉搜索树转换为累加树

创作目的:为了方便自己后续复习重点,以及养成写博客的习惯。

一、修剪二叉搜索树

思路:使用递归的方法,不停的判断节点与所给区间是否相符,相符则对本节点的做右节点做递归操作并返回本节点。

ledcode题目:https://leetcode.cn/problems/trim-a-binary-search-tree/

AC代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
    if(root == NULL) {
        return NULL;
    }
    if(root->val < low) {
        return trimBST(root->right,low,high);
    }else if(root->val > high) {
        return trimBST(root->left,low,high);
    }else {
        root->left = trimBST(root->left,low,high);
        root->right= trimBST(root->right,low,high);
        return root;
    }
}

二、将有序数组转换为二叉搜索树

思路:寻找分割点,分割点作为当前节点,再递归左区间和右区间。

lecode题目:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/

AC代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
 struct TreeNode* helper(int* nums,int left,int right) 
 {
     if(left > right) {
         return NULL;
     }
     //选择中间位置左边的数字作为根节点
     int mid = (left + right) / 2;
     struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
     root->val = nums[mid];
     root->left = helper(nums,left,mid - 1);
     root->right = helper(nums,mid + 1,right);
     return root;
 }
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    return helper(nums,0,numsSize - 1);
}

三、把二叉搜索树转换为累加树

思路:累加的顺序是右中左,反中序遍历二叉树,再顺序累加。

ledcode题目:https://leetcode.cn/problems/convert-bst-to-greater-tree/description/

AC代码:

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

全篇后记:

        二叉树篇章到此结束,收获还是比较大的,坚持下去后面提升会更大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值