leetcode

Convert Sorted Array to Binary Search Tree

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

  1. Get the Middle of the array and make it root.
  2. Recursively do same for left half and right half.
    • Get the middle of left half and make it left child of the root created in step 1.
    • Get the middle of right half and make it right child of the root created in step 1.
    public TreeNode sortedArrayToBST(int[] num) {
        TreeNode node = sortedArrayToBST(num, 0, num.length-1);
        return node;
    }

    public TreeNode sortedArrayToBST(int[] num, int start, int end) {
        if (start>end) return null;
        int middle = start + (end-start)/2;
        TreeNode node = new TreeNode(num[middle]);
        node.left = sortedArrayToBST(num, start, middle-1);
        node.right = sortedArrayToBST(num, middle+1, end);        
        return node;    
    }