108. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

思路: 好中间,先左再右。

public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums==null && nums.length==0) return null;
        TreeNode head = addNode(nums, 0, nums.length-1);
        return head;
    }

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

results matching ""

    No results matching ""