Hii,
I was trying to implement hoffman codes generating program but i was getting runtime error due to function "printcodes " my problem was not to know reason for error but to write printcodes function to print the leaf nodes of the tree created by me with *root as the root node.I don't know if there is any error in huffman tree created by me.Someone please correct my code or atleast provide an easy code for huffman coding as the code i got online is heavy i can't even understand it.Thank you.
I was trying to implement hoffman codes generating program but i was getting runtime error due to function "printcodes " my problem was not to know reason for error but to write printcodes function to print the leaf nodes of the tree created by me with *root as the root node.I don't know if there is any error in huffman tree created by me.Someone please correct my code or atleast provide an easy code for huffman coding as the code i got online is heavy i can't even understand it.Thank you.
Code:
#include<stdio.h> #include<stdlib.h> #include<string.h> struct node{ int fr; int value; struct node *left; struct node *right; }; void printcodes(struct node *p,int top,int arr[]){ if(p->left!=NULL){ arr[top]=0; printcodes(p->left,top+1,arr); } if(p->right!=NULL){ arr[top]=1; printcodes(p->right,top+1,arr); } if(p->left==NULL && p->right==NULL){ for(int i=0;i<top;i++) printf("%d",arr[i]); printf("\n"); } top--; } void heapify(struct node *a[],int n){ int i; for(i=n-1;i>0;i--){ if((a[((i+1)/2)-1]->fr)>(a[i]->fr)) { struct node *t; t = a[((i+1)/2)-1]; a[((i+1)/2)-1]=a[i]; a[i]=t; } } } void heapsort(struct node *a[],int n){ int i; for(i=0;i<2;i++){ heapify(a,n-i); struct node *t; t = a[0]; a[0]=a[n-(i+1)]; a[n-(i+1)]=t; } } int main(){ int i; FILE *fp; char ch; struct node *a[26],*root; int f[26][2]={0}; for(i=0;i<26;i++){ f[i][0]=i; } fp = fopen("input","r"); while((ch=fgetc(fp))!='\n'){ f[ch-'a'][1]++; } for(i=0;i<26;i++){ printf("%d %d\n",f[i][0],f[i][1]); } int count=0; for(i=0;i<26;i++){ if(f[i][1]!=0){ struct node *p; p = (struct node *)malloc(sizeof(struct node)); p->fr = f[i][1]; p->value = f[i][0]; p->left = NULL; p->right = NULL; a[count]=p; count++; } } int send=count; for(i=0;i<count;i++){ heapsort(a,send); struct node *p; p = (struct node *)malloc(sizeof(struct node)); p->fr = a[send-1]->fr + a[send-2]->fr; p->value = -1; p->left = a[send-1]; p->right = a[send-2]; a[send-2]=p; send--; if(i==count-1) root = p; } int arr[26]; printcodes(root,0,arr); }
Comment