I have this homework where I have to convert a min-heap represented in array:
DEFINE #SIZE
typedef int Heap[SIZE]
and implement it in a tree like so:
typedef struct node{
int val;
struct no *left, *right;
} Node, *Tree;
and as a reminder the index of min-heaps arrays is as follows:
#DEFINE PARENT(i) (i-1)/2
#DEFINE LEFT(i) 2*i + 1
#DEFINE RIGHT(i) 2*i + 2
so, how do I do this?
I started on something like this:
Tree heapToTree(int * heap){
Tree *t = malloc(sizeof(struct node));
t->val = heap[0];
Tree *aux = t; //save initial tree position
for(i=0;i<SIZE;i++){
aux->left=malloc(sizeof(struct Node));
aux->left->val=heap[i*2 +1];
aux->right=malloc(sizeof(struct Node));
aux->right->val=heap[i*2 +2];
}
Am I on the right path? I think this should be done recursively, but how?
thanks in advance
There is one thing that you are lacking is - not making the newly created node's links (left
and right
) to the NULL
initially. No matter what, any kind of tree implementation this is very useful - helps in traversal, finding an element (which is again a traversal) etc.
Also in the loop you didn't change the value of aux
(or atleast you didn't show) - as a result you are writing over the old values and having memory leak.
Apart from that not checking the return value of malloc
is another point. You should check the return value of malloc
- if NULL
then you should handle that distinctly (error handling) from that of usual code flow.
Considering that heap is implemented in an array (0-index) you can do this to convert it to tree.
struct node *convIntoTree(int pos,int sz, int *heap){
if(pos >= sz ) return NULL;
struct node* root = malloc(sizeof *root);
if( root == NULL ){
perror("Malloc failed");
exit(EXIT_FAILURE);
}
root->data = heap[pos];
root->left = convIntoTree(pos*2+1,sz);
root->right = convIntoTree(pos*2+2,sz);
return root;
}
Call it like this
struct node *root = convToTree(0,heapsize,heap);
The solution is simply applying a brute force method of traversing every node of the heap and then allocate memory for it and populate it's left and right child recursively.