美文网首页
108. Convert Sorted Array to Bin

108. Convert Sorted Array to Bin

作者: 7ccc099f4608 | 来源:发表于2020-03-16 13:22 被阅读0次

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

image.png

(图片来源https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/

日期 是否一次通过 comment
2020-03-15 0

递归

// BST:左大右小
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums == null) {
            return null;
        }

        return helper(nums, 0, nums.length-1);
    }

    // 二分找到给定区间中间的点
    private TreeNode helper(int[] nums, int sta, int end) {

        if(sta > end) {
            return null;
        }

        int mid = sta + (end-sta)/2;
        TreeNode node = new TreeNode(nums[mid]);

        node.left = helper(nums, sta, mid-1);
        node.right = helper(nums, mid+1, end);

        return node;
    }

相关文章

网友评论

      本文标题:108. Convert Sorted Array to Bin

      本文链接:https://www.haomeiwen.com/subject/cbrgehtx.html