leetcode 108

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

Posted by Static on July 3, 2020

题目链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/

题目描述


分析

1. 添加到数组中,再排序取值


代码实现

public enum  Q108 {
    instance;
    public TreeNode sortedArrayToBST(int[] nums) {
        int l=nums.length;
        TreeNode root=new TreeNode(nums[l/2]);
        fillNode(nums,root,0,l-1);
        return root;
    }


    public TreeNode sortedArrayToBST1(int[] nums) {
        // 左右等分建立左右子树,中间节点作为子树根节点,递归该过程
        return nums == null ? null : buildTree(nums, 0, nums.length - 1);
    }

    private TreeNode buildTree(int[] nums, int l, int r) {
        if (l > r) {
            return null;
        }
        int m = l + (r - l) / 2;
        TreeNode root = new TreeNode(nums[m]);
        root.left = buildTree(nums, l, m - 1);
        root.right = buildTree(nums, m + 1, r);
        return root;
    }



    public static void main(String[] args) {
        Q108.instance.sortedArrayToBST(new int[]{-10,-3,0,5,9});
    }

}

An honest man with ignorance is weak and useless;whereas a learned man with dishonest and fearful. (Britain) Johnson

诚实而无知,是软弱的,无用的;然而有知识而不诚实,那时危险的,可怕的。 – [英] 约翰逊