Given that the input data structure does not guarantee the relationship between parent and children is i*2+1
and i*2+2
, a recursive solution is not really called for. The input sequence represents a breadth-first order, so it would be more natural to build the tree in breadth-first order.
As a side note: the function bit_new
should also initialise the sx
and dx
members: you don't want to leave those with undefined values.
Here is how you could write your algorithm:
Bit_node bit_new(int n) { Bit_node new_node = malloc(sizeof(struct node)); new_node -> n = n; new_node -> sx = NULL; new_node -> dx = NULL; return new_node;} Bit_node bit_arr2tree(int a[], int size) { if (size == 0) { return NULL; } // Create a temporary array to store the node pointers Bit_node nodes[size]; // Create the nodes for (int i = 0; i < size; i++) { nodes[i] = a[i] == -1 ? NULL : bit_new(a[i]); } // To link the nodes, use two indexes: parent and child for (int child = 1, parent = 0; child < size; child += 2, parent++) { // Here we "skip the gaps": a parent cannot be NULL: while (nodes[parent] == NULL) { parent++; } nodes[parent] -> sx = nodes[child]; if (child + 1 < size) { nodes[parent] -> dx = nodes[child + 1]; } } return nodes[0];}