补充完毕,最后一题简单,108根据前面的自己能够勉强写出

669. 修剪二叉搜索树

public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) {
            return null;
        }
        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. 将有序数组转换为二叉搜索树

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

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

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

TreeNode pre;
    public TreeNode convertBST(TreeNode root) {
        travel(root);
        return root;
    }

    public void travel(TreeNode cur){
        if(cur == null){
            return;
        }
        travel(cur.right);
        if(pre !=null){
            cur.val += pre.val;
        }
        pre = cur;
        travel(cur.left);
    }
posted @ 2023-01-06 00:03  维萨斯  阅读(9)  评论(0)    收藏  举报