Sunday, February 19, 2017

Create a binary tree with minimal height

Q: Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.

Ans:

Public TreeNode addToTree(int arr[], int start, int end)
{
     if (start > end) {
         return null;
     }
    int mid = (start + end) / 2;
    TreeNode T = new TreeNode(arr[mid]);
     T.left = addToTree(arr, start, mid - 1);
     T.right = addToTree(arr, mid + 1, end);
     return T;
}


Public TreeNode createBST(int array[]) {
    return addToTree(array, 0, array.length - 1);
}




No comments:

Post a Comment