哈夫曼樹

 
/*博客地址 black4yl.blog.51cto.com*/
 #include "stdio.h"
#include "malloc.h"
#include "string.h"
typedef char* HuffmanCode;/*動態分配數組,存儲哈夫曼編碼*/
typedef struct 
{
char name;/*存放名稱*/
unsigned int weight ;/* 用來存放各個結點的權值*/
unsigned int parent, LChild,RChild ;/*指向雙親、孩子結點的指針*/
}HTNode, * HuffmanTree;/*動態分配數組,存儲哈夫曼樹*/
void Select(HuffmanTree HT,int* s1,int* s2,int n)
{
int min = 32768;
for(int i = 1; i<=n; i++)
{
if( HT[i].weight < min && HT[i].parent == 0)//未分配
{
min = HT[i].weight;
*s1 = i;
}
}/*此時s1 存放最小值下標*/
min = 32768;
for(int i = 1 ;i<=n;i++)
{
if(HT[i].weight < min && HT[i].parent == 0 &&  i  != *s1)
{
min = HT[i].weight;
*s2= i;
}
}
/*此時s2 存放次小值下標*/
}
void CreateHuffTree(HuffmanTree HT,unsigned int* w,int n,char* name)
{
int m,i;
int s1,s2;
/*葉子節點初始化*/
for(i=1;i<=n;i++)
{
HT[i].parent=0;
HT[i].LChild=0;
HT[i].RChild=0;
HT[i].weight = w[i];
HT[i].name = name[i];
}
for(i=n+1;i<2*n;i++)
{
HT[i].parent=0;
HT[i].LChild=0;
HT[i].RChild=0;
HT[i].weight = 0;
}/*非葉子節點初始化*/

for(i=n+1;i<2*n;i++)
{
Select(HT,&s1,&s2,i-1);//找出最小的兩個葉子結點下標
HT[i].LChild = s1;
HT[i].RChild = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
HT[s1].parent = i;
HT[s2].parent = i;
}/*計算權值構建haff樹*/
}
void CreateHuffCode(HuffmanTree HT,HuffmanCode* huffcode,int n )
{
char* cd; //工作區
cd = (char*) malloc(n * sizeof(char));
cd[n-1] = '\0';
int start ;
int c,p;
for(int i =1;i<=n;i++)/*求n 個結點的haff code*/
{
start = n-1;
for(c = i , p=HT[c].parent ; p != 0 ; c=p,p = HT[p].parent)
{
if( HT[p].LChild == c) //當前節點是父節點的左支
{
cd[--start] = '0';
}
else
cd[--start] = '1';
}
huffcode[i] = (char*)malloc((n-start)*sizeof(char));
strcpy(huffcode[i] ,&cd[start]);
}
free(cd);
for(int i =1 ; i<=n;i++)
{  
printf("%c編碼爲%s\n",HT[i].name,huffcode[i]);
}
}
int  main(int argc, _TCHAR* argv[])
{
int n;
unsigned int* w;
char * name;
HuffmanTree HT;
printf("請輸入葉子節點數:");
scanf("%d",&n);
name = (char*) malloc((n+1)*sizeof(char));
w = (unsigned int*)malloc(sizeof( unsigned int)*(n+1));
for(int i=1;i<=n;i++)
{
printf("請輸入葉子節點名稱,權值:");
fflush(stdin);
scanf("%c,%d",&name[i],&w[i]);
}
HT = (HuffmanTree) malloc(sizeof(HTNode)*(2*n));
CreateHuffTree(HT,w,n,name);
HuffmanCode* huffcode = (char**) malloc(sizeof(char*)*(n+1));
CreateHuffCode(HT,huffcode,n);
return 0;
}

wKioL1Rt6omwrrxzAAFqb-UyZV8104.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章