C 将数组中实现的堆转换为树
我有一个家庭作业,其中我必须转换数组中表示的最小堆:C 将数组中实现的堆转换为树,c,algorithm,tree,heap,min-heap,C,Algorithm,Tree,Heap,Min Heap,我有一个家庭作业,其中我必须转换数组中表示的最小堆: 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
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];
}
树堆树(int*heap){
Tree*t=malloc(sizeof(struct node));
t->val=堆[0];
树*aux=t;//保存初始树位置
对于(i=0;ileft=malloc(sizeof(struct Node));
aux->left->val=堆[i*2+1];
aux->right=malloc(sizeof(结构节点));
aux->right->val=堆[i*2+2];
}
我在正确的道路上吗?我认为这应该递归地进行,但是如何进行呢
提前感谢有一点您缺少的是-最初不将新创建的节点链接(
左
和右
)到空
。无论如何,任何类型的树实现都非常有用-有助于遍历、查找元素(这又是一次遍历)等
此外,在循环中,您没有更改aux
(或至少没有显示)的值,因此,您正在写入旧值并出现内存泄漏
除此之外,不检查malloc
的返回值是另一点。您应该检查malloc
的返回值-如果NULL
,那么您应该与通常的代码流区别对待(错误处理)
考虑到堆是在一个数组(0-index)中实现的,您可以将其转换为树
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;
}
这样说吧
struct node *root = convToTree(0,heapsize,heap);
解决方案是简单地应用蛮力方法,遍历堆中的每个节点,然后为其分配内存,并递归地填充其左、右子级。您缺少的一点是-不创建新创建的节点的链接(
左
和右
)无论怎样,任何类型的树实现都非常有用-帮助遍历、查找元素(同样也是遍历)等
此外,在循环中,您没有更改aux
(或至少没有显示)的值,因此,您正在写入旧值并出现内存泄漏
除此之外,不检查malloc
的返回值是另一点。您应该检查malloc
的返回值-如果NULL
,那么您应该与通常的代码流区别对待(错误处理)
考虑到堆是在一个数组(0-index)中实现的,您可以将其转换为树
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;
}
这样说吧
struct node *root = convToTree(0,heapsize,heap);
解决方案是简单地应用蛮力方法,遍历堆的每个节点,然后为其分配内存,并递归地填充其左右子节点。什么是
struct no
?堆是一种树…也就是说,我不明白为什么要将具有紧凑表示形式的树转换为不具有紧凑表示形式的树。这是作业。我想这是为了更好地理解主题什么是struct no
?堆是一种树…也就是说,我不明白为什么你想把一棵有紧凑表示的树转换成一棵没有紧凑表示的树。这是家庭作业。我想这是为了更好地理解subject@Richard.:检查它。很好的想法设置索引作为参数。非常感谢much@Richard.:检查它。很好,将索引设置为t他说,非常感谢