我有这个作业,我必须转换以数组表示的最小堆:
DEFINE #SIZE
typedef int Heap[SIZE]
并像这样在树中实现它:
typedef struct node{
int val;
struct no *left, *right;
} Node, *Tree;
提醒一下,最小堆数组的索引如下:
#DEFINE PARENT(i) (i-1)/2
#DEFINE LEFT(i) 2*i + 1
#DEFINE RIGHT(i) 2*i + 2
那么,我该怎么做呢?
我开始这样的事情:
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];
}
我在正确的道路上吗?我认为这应该递归地完成,但是如何呢?
提前致谢