代码随想录第二十三天|669.修剪二叉树,108.将有序数组转换为二叉搜索树,538.将二叉搜索树转换为累加树

669. 修剪二叉搜索树 - 力扣(Leetcode)

class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if(root==NULL) return NULL;
        if(root->valright, 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. 将有序数组转换为二叉搜索树 - 力扣(Leetcode) 

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

538. 把二叉搜索树转换为累加树 - 力扣(Leetcode)

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

 

你可能感兴趣的:(代码随想录,leetcode,算法,c++)