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

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

669. 修剪二叉搜索树

题目链接

提交代码

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

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

题目链接

提交代码(方法)

class Solution {
private:
    TreeNode* traversal(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 = traversal(nums, left, mid - 1);
        root->right = traversal(nums, mid + 1, right);
        return root;
    }
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        TreeNode* root = traversal(nums, 0, nums.size() - 1);
        return root;
    }
};

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

题目链接

提交代码(方法)

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

总结

                     日期: 2023 年 4 月 4 日
              学习时长: 0 h 30 m
                     难度: ★ \bigstar
累计完成题目数量: 60
距离目标还有数量: 240
                      小结:

你可能感兴趣的:(算法,leetcode,贪心算法)