day17打卡

ikun1111發表於2024-09-08
  1. 修剪二叉搜尋樹

/**

  • Definition for a binary tree node.

  • struct TreeNode {

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

         TreeNode *right = trimBST(cur, low, high);
         return right;
     }
     if(root->val > high)
     {
         TreeNode *cur = root->left;
         
         TreeNode *left = trimBST(cur, low, high);
         return left;
    
     }
     root->left = trimBST(root->left, low, high);
     root->right = trimBST(root->right, low, high);
     return root;
    

    }
    };

2.將有序陣列轉化為二叉搜尋樹

/**

  • Definition for a binary tree node.
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode() : val(0), left(nullptr), right(nullptr) {}
    
  • TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    
  • TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    
  • };
    */
    class Solution {
    public:
    TreeNode *traversal(vector& nums, int low, int high)
    {
    if(low <= high)
    {
    int mid = low + ((high - low) / 2);
    TreeNode root = new TreeNode(nums[mid]);
    root->left = traversal(nums, low, mid-1);
    root->right = traversal(nums, mid+1, high);
    return root;
    }
    return nullptr;
    }
    TreeNode
    sortedArrayToBST(vector& nums) {
    return traversal(nums, 0, nums.size()-1);
    }
    };

3.將二叉搜尋樹轉化為累加樹
/**

  • Definition for a binary tree node.
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode() : val(0), left(nullptr), right(nullptr) {}
    
  • TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    
  • TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    
  • };
    /
    class Solution {
    public:
    TreeNode
    convertBST(TreeNode* root) {
    if(root == nullptr)
    {
    return nullptr;
    }
    root->right = convertBST(root->right);
    if(pre)
    {
    root->val += pre->val;
    }
    pre = root;
    root->left = convertBST(root->left);
    return root;
    }
    private:
    TreeNode *pre = nullptr;
    };