Huffman Tree 简单构造

时间:2021-07-12 08:08:58
//函数:构造Huffman树HT[2*n-1]
#define MAXVALUE 9999//假设权值不超过9999
#define MAXLEAF 30
#define MAXNODE MAXLEAF*2-1
using namespace std;
#include <iostream> //Using cin or cout
#include <malloc.h> //Using malloc and realloc
#include <stdio.h> //Using c
#include <stdlib.h> typedef struct
{
int weight;//权值
int parent;//父结点下标
int lchild;//左孩子下标
int rchild;//右孩子下标
}HTNode; void HuffmanTree(HTNode HT[], int n)
{
int i,j,x1,x2;
int m1,m2;
for(i=1;i<=n-1;++i)//n-1个非叶子结点
{
m1=m2=MAXVALUE; x1=x2=0; //m1,m2用来记录结点中最小的权值,x1,x2用来记录其左右子树结点
for(j=1;j<n+i;++j)
{ if(HT[j].parent==0)
{ if (HT[j].weight<m1) {m2=m1; x2=x1;m1=HT[j].weight; x1=j;}
else if(HT[j].weight<m2) { m2=HT[j].weight; x2=j;}
}
}
HT[x1].parent=n+i;
HT[x2].parent=n+i;
HT[n+i].weight = HT[x1].weight + HT[x2].weight;
HT[n+i].lchild=x1;
HT[n+i].rchild=x2;
}//外层for循环结束 }
//函数:求Huffman树HT[n]的Huffman编码
#define MAXBIT 20
typedef struct
{
int bit[MAXBIT];
int start;
}HCodeType; void HuffmanCode (HTNode HT[], int n, HCodeType HuffCode[])
{
HCodeType cd; int i,j,c,p;
for(i=1;i<=n;++i)
{
cd.start=n; c=i; p=HT[c].parent;//p为c双亲
while(p!=0)
{
if(HT[p].lchild==c) cd.bit[cd.start]=0;
else cd.bit[cd.start]=1;
cd.start--; c=p; p=HT[c].parent ;//保持p为c双亲
}
for(j=cd.start+1;j<=n;j++) HuffCode[i].bit[j]=cd.bit[j];
HuffCode[i].start=cd.start;
}
for(i=1;i<=n;++i)
{
cout<<"第"<<i<<"个字符的哈夫曼编码为:";
for(int j=HuffCode[i].start+1;j<=n;j++)
{ cout<<HuffCode[i].bit[j];
//printf("%d",HuffCode[i].bit[j]);
}
cout<<endl;
}
}
int main()
{
int n=8;
HTNode HT[MAXNODE];
for(int i=1; i<=2*n-1; ++i) //初始化
{
HT[i].weight=0; HT[i].parent=0;
HT[i].lchild=0; HT[i].rchild=0;
}
for(int i=1;i<=n;++i)
{
cout<<"请输入第"<<i<<"个值为:"<<endl;
scanf("%d",&HT[i].weight);
if(HT[i].weight>=MAXVALUE)
{
printf("超过权值允许的最大值,重新输入!\n");
--i;
}
}
HuffmanTree(HT,n);
HCodeType HuffCode[MAXNODE];
HuffmanCode (HT,n,HuffCode);
}