算法刷题 DAY23

669. 修剪二叉搜索树

struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {

    if (!root)
        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;
}
    
}

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

struct TreeNode* create_AVL(int *nums,int left,int right){

    if(left>right) return NULL;//终止条件
    
    //处理当前结点
    int mid=(left+right)/2;
    struct TreeNode* node=(struct TreeNode*)calloc(1,sizeof(struct TreeNode));
    node->val=nums[mid]; 
    //左闭右开
    //递归处理并连接左右子树
    node->left=create_AVL(nums,left,mid-1);
    node->right=create_AVL(nums,mid+1,right);

    return node;

}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    
    return create_AVL(nums,0,numsSize-1);
}

538.把二叉搜索树转换为累加树


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

//倒序遍历(从最大的开始遍历):右中左
void change_BST(struct TreeNode* root, int* pre) {

    if (!root)
        return;

    change_BST(root->right, pre);

    root->val += (*pre);
    *pre = root->val;

    change_BST(root->left, pre);
}

struct TreeNode* convertBST(struct TreeNode* root) {

    int pre = 0;
    change_BST(root, &pre);
    //pre是全局性的→用指针
    return root;
}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值