【c++刷题笔记-二叉树】day21: 669. 修剪二叉搜索树 、108.将有序数组转换为二叉搜索树 、 538.把二叉搜索树转换为累加树

669. 修剪二叉搜索树 - 力扣(LeetCode)

思路:当前结点大于有右边界时直接返回它的左子树,小于左边界时返回当前结点的右子树

重点:使用左右结点接受返回的结点覆盖结点,删除需要删除的结点

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if(root==nullptr){
            return root;
        }
        if(root->val>high){
            return trimBST(root->left,low,high);
        }
        if(root->val<low){
            return trimBST(root->right,low,high);;
        }
        root->left=trimBST(root->left,low,high);
        root->right=trimBST(root->right,low,high);
        return root;
    }
};

108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)

思路:二分法建树,左闭右闭区间

重点:平衡二叉搜索树

class Solution {
public:
    TreeNode* fun(vector<int>& nums,int left,int right){
        if(left>right){
            return nullptr;
        }
        int mid=left+(right-left)/2;
        TreeNode* root=new TreeNode(nums[mid]);
        root->left=fun(nums,left,mid-1);
        root->right=fun(nums,mid+1,right);
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return fun(nums,0,nums.size()-1);;
    }
};

538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)

思路:累加树是中序遍历后,从后向前累加,结点的值为后缀和,使用一个额外变量存放累加和,进行反中序遍历时进行赋值

重点:反中序遍历,全局变量存储累加和

class Solution {
public:
    int pre=0;
    TreeNode* convertBST(TreeNode* root) {
        if(root==nullptr){
            return nullptr;
        }
        convertBST(root->right);
        pre+=root->val;
        root->val=pre;
        convertBST(root->left);
        return root;
    }
};

 总结

建树和修改树,可以考虑使用左右子树接受递归的值,达到删除和修改的要求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值