代码随想录算法训练营Day21 | 669. 修剪二叉搜索树 | 108.将有序数组转换为二叉搜索树 | 538.把二叉搜索树转换为累加树

今日任务

669. 修剪二叉搜索树

Code

cpp 复制代码
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if(root == nullptr){
            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.将有序数组转换为二叉搜索树

Code

cpp 复制代码
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {

        function<TreeNode *(int , int)> dfs = [&](int low, int high) -> TreeNode *{
            if(low > high){
                return nullptr;
            }
            int mid = low + (high - low) / 2;
            TreeNode *left = dfs(low, mid - 1);
            TreeNode *right = dfs(mid + 1, high);
            return new TreeNode(nums[mid], left, right);
        };
        return dfs(0, nums.size() - 1);
    }
};

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

Code

cpp 复制代码
class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        int sum = 0;
        function<void(TreeNode *)> dfs = [&](auto node)->void{
            if(node == nullptr){
                return;
            }
            dfs(node->right);
            sum += node->val;
            node->val = sum;
            dfs(node->left);
        };
        dfs(root);
        return root;
    }
};
相关推荐
CS创新实验室10 分钟前
《计算机网络》深入学:路由算法与路径选择
网络·计算机网络·算法
一条大祥脚10 分钟前
ABC357 基环树dp|懒标记线段树
数据结构·算法·图论
tod11310 分钟前
力扣高频 SQL 50 题阶段总结(四)
开发语言·数据库·sql·算法·leetcode
naruto_lnq21 分钟前
C++中的桥接模式
开发语言·c++·算法
苦藤新鸡21 分钟前
50.腐烂的橘子
数据结构·算法
想进个大厂27 分钟前
代码随想录day32 动态规划01
算法·动态规划
j4455661140 分钟前
C++中的职责链模式高级应用
开发语言·c++·算法
uesowys43 分钟前
Apache Spark算法开发指导-Decision tree classifier
算法·决策树·spark
池央1 小时前
贪心算法-最大数
算法·贪心算法
iAkuya1 小时前
(leetcode)力扣100 57电话号码的字母组合(回溯)
算法·leetcode·深度优先