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.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums == null) return null;
        return subArrayBuilder(nums, 0, nums.length - 1);

    }

    private TreeNode subArrayBuilder(int[] nums, int left, int right){
        if(left > right) return null;
        if(left == right) return new TreeNode(nums[left]);

        int mid = left + (right-left)/2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = subArrayBuilder(nums, left, mid-1);
        root.right = subArrayBuilder(nums, mid+1, right);

        return root;
    }

}

results matching ""

    No results matching ""