Web Toolbar by Wibiya

Pages

Tuesday, May 17, 2011

Given a sorted array in ascending order, write a function to create a binary tree having minimal height from this array.

Solution #1: We are asked to create a balanced tree to keep the height minimal. The balanced tree can be created by inserting the middle element first and then subsequently adding the left and right half of the array. This problem again demands recursion. The algorithm will look like this:-

- Insert middle element
- Insert left-half
- Insert right-half

Here is the code,
int arr[100] = {0,};

void insertArrElement(node **ptrRoot, int* arrPtr, int start, int end)
{
    if(start > end)
        return;

    int mid = (start+end)/2;
    insert(ptrRoot, arr[mid]);
    insertArrElement(&((*ptrRoot)->left), arrPtr, start, mid-1);
    insertArrElement(&((*ptrRoot)->right), arrPtr, mid+1, end);

    return;
}

int main()
{
    int i=0;
    for(i=0; i<100; i++)
        arr[i] = i;

    node* root = NULL;

    insertArrElement(&root, arr, 0, 99);
    
    return 1;
}

No comments: