标签:哈夫曼树
/*博客地址 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; }
本文出自 “black4yL” 博客,请务必保留此出处http://black4yl.blog.51cto.com/4222963/1580286
标签:哈夫曼树
原文地址:http://black4yl.blog.51cto.com/4222963/1580286