package buildingblock.divideandconquer.lc108_convertsortedarraytobinarysearchtree;

import fundamentals.tree.TreeNode;

/**
 * Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
 */
public class Solution {

    // My 2nd: O(N) time, O(logN) space
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 0) {
            return null;
        }
        return doConvertToBST(nums, 0, nums.length - 1);
    }

    private TreeNode doConvertToBST(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }

        int mid = start + (end - start) / 2;

        TreeNode root = new TreeNode(nums[mid]);
        root.left = doConvertToBST(nums, start, mid - 1);
        root.right = doConvertToBST(nums, mid + 1, end);
        return root;
    }

    // My 1st
    public TreeNode sortedArrayToBST1(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return doSortedArrayToBST(nums, 0, nums.length-1);
    }

    private TreeNode doSortedArrayToBST(int[] nums, int low, int high) {
        if (low == high) {          // Could speed up, but not a must
            return new TreeNode(nums[low]);
        } else if (low > high)  {
            return null;
        }

        int mid = (low + high) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = doSortedArrayToBST(nums, low, mid-1);
        root.right = doSortedArrayToBST(nums, mid+1, high);
        return root;
    }

}

@@ -247,16 +247,425 @@
 tion %7B%0A%0A
+    // %5B%5D, %5B1%5D, %5B1,2%5D, %5B1,2,3%5D, %5B1,2,3,4%5D%0A    public TreeNode sortedArrayToBST(int%5B%5D A) %7B%0A        return build(A, 0, A.length - 1);%0A    %7D%0A%0A    private TreeNode build(int%5B%5D A, int l, int r) %7B%0A        if (l %3E r) return null;%0A        int m = l + (r - l) / 2;%0A        TreeNode root = new TreeNode(A%5Bm%5D);%0A        root.left = build(A, l, m - 1);%0A        root.right = build(A, m + 1, r);%0A        return root;%0A    %7D%0A%0A
     // M
@@ -724,32 +724,33 @@
 sortedArrayToBST
+2
 (int%5B%5D nums) %7B%0A 

convert sorted array to binary search tree