代码随想录算法训练营第二十一天|二叉树 part8

669. 修剪二叉搜索树

其实就是判断当前节点的值与搜索区间的关系。

  1. 位于 [ l o w , h i g h ] [low, high] [low,high]: 继续遍历修剪左子树和右子树
  2. 位于 ( − ∞ , l o w ) (-\infty, low) (,low): 返回修剪的右子树
  3. 位于 ( h i g h , + ∞ ) (high, +\infty) (high,+): 返回修剪的左子树
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if (root == nullptr)
            return nullptr;
        if (root->val < low)
            return trimBST(root->right, low, high);
        else if (root->val > high)
            return trimBST(root->left, low, high);
        else {
            root->left = trimBST(root->left, low, high);
            root->right = trimBST(root->right, low, high);
        }
        return root;
    }
};

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

本质就是寻找分割点,分割点作为当前节点,然后递归左区间和右区间。

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

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

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

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