代码随想录算法训练营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;
    }
};
相关推荐
小开不是小可爱21 分钟前
leetcode_383. 赎金信_java
java·数据结构·算法·leetcode
√尖尖角↑4 小时前
力扣——【1991. 找到数组的中间位置】
算法·蓝桥杯
Allen Wurlitzer4 小时前
算法刷题记录——LeetCode篇(1.8) [第71~80题](持续更新)
算法·leetcode·职场和发展
百锦再6 小时前
五种常用的web加密算法
前端·算法·前端框架·web·加密·机密
碳基学AI7 小时前
北京大学DeepSeek内部研讨系列:AI在新媒体运营中的应用与挑战|122页PPT下载方法
大数据·人工智能·python·算法·ai·新媒体运营·产品运营
独家回忆3647 小时前
每日算法-250410
算法
袖清暮雨7 小时前
Python刷题笔记
笔记·python·算法
风掣长空8 小时前
八大排序——c++版
数据结构·算法·排序算法
流星白龙9 小时前
【C++算法】50.分治_归并_翻转对
c++·算法
Java致死10 小时前
费马小定理
算法·费马小定理