108. Convert Sorted Array to Bin

2020-03-16  本文已影响0人  7ccc099f4608

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;
    }
上一篇 下一篇

猜你喜欢

热点阅读