Making a binary tree using an array in C If I want to make a binary tree from an array in the following order:

Example: for the following array: { -1, 17, -1, 3, -1, -1, -1, 55, -1, 4, -1, 15, 11, 2, 3 } the following tree is created:

           55

     15         3

  2     4     *    17

3 11  *   *      *    *


The function is recursive and returns a Tree input: the array and it's size. The tree nodes can only receive positive values from the array so -1 wont be considered. * means NULL prototype: Tree BuildTreeFromArray(int *arr, int size).

Would very much appreciate the help.

This is what I had so far and it's working but I don't really like it.

Tree BuildTreeFromArray(int  *arr, int  size)
{
    Tree resTree;
    Tree right;
    Tree left;
    resTree.root = (TreeNode*)malloc(sizeof(TreeNode));
    checkMemoryAllocation(resTree.root);
    int halfSize;

    if (size == 1)
    {
        resTree.root-&gt;data = arr[0];
        resTree.root-&gt;left = NULL;
        resTree.root-&gt;right = NULL;
    }
    else
    {
        halfSize = size / 2;
    resTree.root-&gt;data = arr[halfSize];

    if (arr[halfSize/2] != -1)
    {//we check if there's a valid array data we can input to the tree
        left = BuildTreeFromArray(arr, halfSize);
        resTree.root-&gt;left = left.root;
    }
    else
        resTree.root-&gt;left = NULL;

    if (arr[halfSize + (halfSize / 2) + 1] != -1)
    {
        right = BuildTreeFromArray(arr + halfSize + 1, halfSize);
        resTree.root-&gt;right = right.root;
    }
    else
        resTree.root-&gt;right = NULL;

    }
    return resTree;
}


Could this be written in a different version?
Do not cast the malloc value. It serves no purpose, and may mask a serious problem.
Allocating sizeof(TreeNode) assumes the knowledge of the type of resTree.root, and results in the double maintenance. A preferred idiom is malloc(sizeof(*resTree.root)).
As written, the node tests for validity of its (future) children. It is more natural for the node to test its own validity:

if (size == 0) {
    return NULL;
}

halfSize = size/2;
if (arr[halfSize == -1) {
    return NULL;
}

resTree.root = malloc(sizeof(*resTree.root));
resTree.root-&gt;data = data;
resTree.root-&gt;left = BuildTreeFromArray(....).root;
resTree.root-&gt;right = BuildTreeFromArray(....).root;

return resTree;

I don see a reason why TreeNode is wrapped into Tree. More context would be nice.