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

669.修剪二叉树

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

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

思路:这就是构建二叉树,关键点就是找到每棵树的根节点,以及如何分割出左子树和右子树!

class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.size()==0)return nullptr;
        if(nums.size()==1)
        {
            TreeNode* node=new TreeNode(nums[0]);
            return node;
        }
        int rootvalue=nums[nums.size()/2];
        TreeNode* root=new TreeNode(rootvalue);
        vector<int> left(nums.begin(),nums.begin()+nums.size()/2);
        vector<int> right(nums.begin()+nums.size()/2+1,nums.end());
        root->left=sortedArrayToBST(left);
        root->right=sortedArrayToBST(right);
        return root;
    }
};

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

思路:中序遍历是关键!

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

你可能感兴趣的:(算法)