Wednesday, December 9, 2015

Insert Sorted Array into a Binary Search Tree with minimum height

public class BinarySearchTree {
    BinarySearchTree left, right;
    int data;
    public BinarySearchTree(int... SortedArrayOfdata) {
        int mid=SortedArrayOfdata.length/2;
        this.left=null;
        this.right=null;
        this.data=SortedArrayOfdata[mid];
        insertSortedArray(SortedArrayOfdata, 0, mid-1);
        insertSortedArray(SortedArrayOfdata, mid+1, SortedArrayOfdata.length-1);
    }
    private void insertSortedArray(int[] a, int startIndex, int endIndex)    {
        if(startIndex<=endIndex)    {
            int mid=(startIndex+endIndex)/2;
            insert(a[mid]); //Insert method is available here: link
            insertSortedArray(a, startIndex, mid-1);
            insertSortedArray(a, mid+1, endIndex);
        }
    }

}

Example Input:
BinarySearchTree BST = new BinarySearchTree(0,1,2,3,4,5,6,7,8,9,10,11,12,13);
UA-39217154-2