代码随想录算法训练营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;
    }
};
相关推荐
苏言の狗16 分钟前
小R的并集大小期望计算 | 蛮力
数据结构·算法
BineHello22 分钟前
MPC用优化求解器 - 解决无人机轨迹跟踪
算法·矩阵·自动驾驶·动态规划·无人机
誓约酱24 分钟前
(每日一题) 力扣 14 最长公共前缀
算法·leetcode·职场和发展
冠位观测者1 小时前
【Leetcode 每日一题 - 补卡】2070. 每一个查询的最大美丽值
数据结构·算法·leetcode
誓约酱1 小时前
(每日一题) 力扣 860 柠檬水找零
linux·c语言·c++·算法·leetcode·职场和发展
地平线开发者1 小时前
手把手基于 MINI 数据集带你做一次板端精度评估
算法·自动驾驶
詹天佐1 小时前
ICCE 数字车钥匙介绍
人工智能·算法
ak啊1 小时前
记忆化(Memoization)
算法
moonless02222 小时前
【Python】你还不了解数据结构与算法?
数据结构·算法·编程语言
z_y_j2299704382 小时前
L1-039 古风排版
c语言·数据结构·算法