力扣打卡Day23 二叉树Part08 修剪二叉搜索树+将有序数组转换为二叉搜索树+把二叉搜索树转换为累加树

二叉树Part08

  • 修剪二叉搜索树
  • 将有序数组转换为二叉搜索树
  • 把二叉搜索树转换为累加树

修剪二叉搜索树

669. 修剪二叉搜索树

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);
        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. 将有序数组转换为二叉搜索树

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

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

538. 把二叉搜索树转换为累加树
没看懂题意。
用pre记录前一个节点的数值。

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* convertBST(TreeNode* root) {
        pre = 0;
        traversal(root);
        return root;
    }
};
···

你可能感兴趣的:(leetcode,算法,职场和发展)