//赫夫曼树和赫夫曼编码。可运行代码 #include<iostream> using namespace std; typedef struct{ unsigned int weight; unsigned int parent,lchild,rchild; }HTNode,*HuffmanTree; //动态分配数组存储赫夫曼树 typedef char **HuffmanCode; //动态分配数组存储赫夫曼编码 //在HT[1..t]中选择parent为0且weight最小的两个节点,其序号分别为s1和s2 void Select(HuffmanTree HT,int t, int &s1,int &s2) { int i; for(i=1;i<=t-1;i++) { if(HT[i].parent==0) { s1=i; break; } } for(i=s1+1;i<=t;i++) { if(HT[i].parent==0) { s2=i; break; } } for(i=s1+1;i<=t;i++) { if(HT[i].weight<=HT[s1].weight&&HT[i].parent==0) { s2=s1; s1=i; } else if(HT[i].weight<=HT[s2].weight&&HT[i].parent==0) { s2=i; } } } //求赫夫曼编码的函数 void HuffmanCoding(HuffmanTree &HT, HuffmanCode &HC,int *w,int n) { if(n<=1) return; int m=2*n-1; /*赫夫曼树的总结点数目为2n-1*/ HTNode* p; int i,s1,s2; HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); //0号单元未用 for(p=HT+1,i=1;i<=n;i++,p++,w++) { (*p).weight=*w; (*p).lchild=0; (*p).rchild=0; (*p).parent=0; } //w自增的顺序问题 for(i=n+1;i<=m;i++,p++) { (*p).weight=0; (*p).lchild=0; (*p).rchild=0; (*p).parent=0; } for(i=n+1;i<=m;i++) //建立赫夫曼树 { Select(HT,i-1,s1,s2); 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; } //从叶子逆向到根求每个字符的赫夫曼编码 HC=(HuffmanCode)malloc((n+1)*sizeof(char*)); //分配n个字符编码的头指针向量 char* cd=(char*)malloc(n*sizeof(char)); //分配求编码的工作空间 cd[n-1]='