Day21 669. 修剪二叉搜索树 | 108. 将有序数组转换为二叉搜索树 | 538. 把二叉搜索树转换为累加树

54 阅读1分钟

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

class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null)
            return null;
        if (root.val < low)
            return trimBST(root.right, low, high);
        else if (root.val > high)
            return trimBST(root.lefg, low, high);
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return sortedArrayToBST(nums, 0, nums.length);
    }

    public TreeNode sortedArrayToBST(int[] nums, int left, int right) {
        if (left >= right)
            return null;
        if (right - left == 1)
            return new TreeNode(nums[left]);
        int mid = left + (right - left) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sortedArrayToBST(nums, left, mid);
        root.right = sortedArrayToBST(nums, mid + 1, right);
        return root;
    }
}

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

class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if(root != null){
            //先遍历右子树
            convertBST(root.right);
            //更新当前节点的值
            sum += root.val;
            root.val = sum;
            //再遍历左子树
            convertBST(root.left);
        }
        return root;
    }
}

这个累加树题目一时难以明白。