1. 程式人生 > >哈夫曼樹的建立以及編碼

哈夫曼樹的建立以及編碼

在codeblocks下編譯執行通過。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct{
    int weight;
    int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char **HuffmanCode;


int min1(HuffmanTree t,int i)
{//函式VOID select呼叫
   int j,flag;
   int k=10000;//取K為最小可能的值
   for(j=1;j<=i;j++)
     if(t[j].weight<k && t[j].parent==0)
        {
           k=t[j].weight;
           flag=j;
        }
        t[flag].parent=1;
        return flag;
}

void Select(HuffmanTree HT,int i,int *s1,int *s2)
{
   int j;
   *s1=min1(HT,i);
   *s2=min1(HT,i);
   if(*s1>*s2)
   {
       j=*s1;
      *s1=*s2;
      *s2=j;
   }
}

//建立哈夫曼樹
void CreateHuffmanTree(HuffmanTree *HT,int *w,int n){
    int i,s1,s2,k,f;
    if(n<=1) printf("error");
    int m;
    m=2*n-1;
    HTNode *p;
    *HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));
    for(p=*HT+1,i=1;i<=n;i++,p++,w++){
        p->weight=*w;
        p->parent=0;
        p->lchild=0;
        p->rchild=0;
    }
    for(;i<=m;i++,p++){
        p->weight=0;
        p->parent=0;
        p->lchild=0;
        p->rchild=0;
    }

    //在HT[1...i-1]中選擇parent為0且權值最小的兩個節點,序號分別為s1,s2;
    for(i=n+1;i<=m;i++){
    printf("1111111");
        Select(*HT,i-1,&s1,&s2);
    printf("222222");
        HT[s1]->parent = i;  printf("333333");HT[s2]->parent = i;
        HT[i]->lchild = s1;   HT[i]->rchild = s2;
        HT[i]->weight = HT[s1]->weight + HT[s2]->weight;
    }
}

//得到Huffman編碼
void HuffmanTreeCode(HuffmanTree *HT,HuffmanCode *HC,int n){
   int start,c,i,f;
   char *cd;
   *HC=(HuffmanCode)malloc((n+1)*sizeof(char *));
   cd=(char *)malloc(n*sizeof(char));
   cd[n-1]='\0';
   for(i=1;i<=n;i++){
        start =n-1;
        for(c=i,f=HT[i]->parent;f!=0;c=f,f=HT[f]->parent){
            if(HT[f]->lchild==c) cd[--start]='0';
            else cd[--start]='1';
        }
        *HC[i]=(char *)malloc((n-start)*sizeof(char));
        strcpy(*HC[i],&cd[start]);
   }
   free(cd);
   //列印哈夫曼編碼
   printf("number\t\tweight\t\tCode\n");
   for(i=1;i<=n;i++){
    printf("%d\t\t%d\t\t%d\n",i,HT[i]->weight,HC[i]);
   }
}

void ShowHuffmanTree(HuffmanTree HT,int n){
    int i;
    printf("赫夫曼樹如下:\n");
    printf("number\t\tweight\t\tparent\t\tlchild\t\trchild\n");
    for(i=1;i<=2*n-1;i++){
        printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\n",i,HT[i].weight,HT[i].parent,HT[i].lchild,HT[i].rchild);
    }
}

void main(){
    int i,n;
    int *w;
    printf("請輸入節點個數n(n>1):");
    scanf("%d",&n);
    w=(int *)malloc((n+1)*sizeof(int));
    w[0]=0;
    printf("請輸入對應的權值:");
    for(i=1;i<=n;i++){
        scanf("%d",&w[i]);
    }
    HuffmanCode HC=NULL;
    HuffmanTree HT=NULL;
    CreateHuffmanTree(&HT,w,n);
    HuffmanTreeCode(&HT,&HC,n);
    ShowHuffmanTree(HT,n);
}