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

文档讲解: 代码随想录

视频讲解:你修剪的方式不对,我来给你纠正一下!| LeetCode:669. 修剪二叉搜索树_哔哩哔哩_bilibili

 构造平衡二叉搜索树!| LeetCode:108.将有序数组转换为二叉搜索树_哔哩哔哩_bilibili

普大喜奔!二叉树章节已全部更完啦!| LeetCode:538.把二叉搜索树转换为累加树_哔哩哔哩_bilibili


第21天,抽空赶紧补一补。

669.修剪二叉搜索树

思路:

class solution{
public:
    TreeNode* traversal(TreeNode* root, int low, int high){
        if(root == NULL) return NULL;
        if(root->val < low){
            TreeNode* right = traversal(root->right, low, high);
            return right;
        }
        if(root->val > high){
            TreeNode* left = traversal(root->left, low, high);
            return left;    
        }            
        root->left=traversal(root->left, low, high);
        root->right=traversal(root->right, low, high);
        return root;
    }
};

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

思路:删除和增加二叉树节点均用递归实现,分割数组,从中选取一个元素为根节点,依次向下遍历再分割,边界采取左闭右闭原则。

class solution{
private:
    Treenode* traversal(vector& nums, int left,int right){
        if(left > right) return NULL;
        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& nums){
        Treenode* root = traversal(nums, 0, nums.size() - 1);
        return root;
    }
};

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

思路:把二叉树想像成数组,再从右往左累加。

class solution{
private:
    int pre = 0;
    void traversal(TreeNode* cur){
        if(cur == NULL) return;
        traversal(cur->right);
        cur->val += pre;
        pre = cur->val;
        traversal(cur->left);
    }
public:
    TreeNode* converBST(TreeNode* root){
        pre = 0;
        traversal(root);
        return root;
    }
};

总结:要准备期中考试了,好难分出心思刷题...呜呜

你可能感兴趣的:(算法,leetcode,数据结构)