I wish to implement a Huffman tree. But it seems like my program can't work correctly. I've been struggling with it for days!
(Segmentation Fault) I guess there are some mistakes with the space of pointers, but I just don't know what's the problem.
(btw,I printed all the nodes in the tree which is not exact hufftree. Well, it doesn't matter)
Code:
#include<stdio.h>
#include<malloc.h>
typedef struct huff{
struct huff *left;
struct huff *right;
int data;
} make;
make *initial(int x[],int number);
void print(make *c);
int main(){
int p,q[p];
scanf("%d",&p);
int delta;
for(delta=0;delta<p;delta++){
scanf("%d",&q[delta]);
}
make *root;
root=initial(q,p);
print(root);
return 0;
}
make *initial(int x[],int number){
make *y[number];
int k;
for(k=0;k<=number-1;k++){
y[k]=(make *)malloc(sizeof(make));
y[k]->data=x[k];
y[k]->left=y[k]->right=NULL;
}
while(number>1){
int i,j;
make *t;
for(j=number-1;j>=1;j--){
for(i=0;i<=j-1;i++){
if(y[i]->data>y[i+1]->data){
t=y[i+1];
y[i+1]=y[i];
y[i]=t;
}
else {}
}
}
make *p;
p=(make *)malloc(sizeof(make));
p->left=y[0];
p->right=y[1];
p->data=x[0]+x[1];
number--;
if(number>=3){
y[0]=p;
int se;
for(se=1;se<=number-2;se++){
y[se]=y[se+1];
}
}
else{}
}
make *q;
q=(make *)malloc(sizeof(make));
q->left=y[0];
q->right=y[1];
return (q);
}
void print(make *c){
if(c!=NULL){
printf("%d,",c->data);
print(c->left);
print(c->right);
}
else{}
}