代码随想录训练营第二十三天|669.修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树

669.修剪二叉搜索树

链接:LeetCode669.修剪二叉搜索树

不能仅仅只能遇到不满条件的节点就返回nullptr,因为不满足条件节点的左右子树中可能有满足条件的节点。可以“不删除不满足条件的节点”,而是寻找“满足条件的节点”

class Solution {
public:
    //不用删除节点,只需要找到满足条件的节点即可
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if(!root) return root;
        if(root->val<low) {
            return trimBST(root->right,low,high);
        }
        if(root->val>high) {
            return trimBST(root->left,low,high);
        }
        root->left = trimBST(root->left,low,high);
        root->right = trimBST(root->right,low,high);

        return root;
    }
};

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

链接:LeetCode108将有序数组转换为二叉搜索树
采用递归

class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return builtBST(nums,0,nums.size()-1);
    }
private:
    TreeNode *builtBST(vector<int>&nums,int st,int ri){
        //递归终止边界
        if(st>ri) return nullptr;
        int mid = ((ri-st)>>1) + st;
        TreeNode * node = new TreeNode(nums[mid]);
        node->left = builtBST(nums,st,mid-1);
        node->right = builtBST(nums,mid+1,ri);

        return node;
    }
};

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

链接:LeetCode538.把二叉搜索树转换为累加树
思路:
若是按照标准的中序遍历(左中右),需要先遍历整棵树,计算出所有节点的数值和,然后再次中序遍历并且记录遍历过节点的数值和presum,当前节点的数值变为sum-presum。实现起来较为繁琐。
所以采用“右中左”的类似中序遍历的方式遍历这棵树,便利的同时只需要计算遍历过节点的数值和即可。

class Solution {
public:
    int cursum = 0;
    TreeNode* convertBST(TreeNode* root) {
        if(!root) return root;

        root->right = convertBST(root->right);
        int te = root->val;
        if(cursum) root->val += cursum;
        cursum+=te;
        root->left = convertBST(root->left);

        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值