//Huffman tree
#include <iostream>
#include <vector>
const int MaxN=100;//设定的最大节点个数
const int Maxbit=255;//设定最大编码值
const int MaxValue=9999;//设定权重最大值
using namespace std;
struct HaffNode{
int weight;//权值
int flag;//标记
int parent;
int leftChild;
int rightChild;
HaffNode(){
}
};
struct Code{
int bit[MaxN];
int start;
int weight;//编码的起始下标
Code()
{
}
};
void Haffman(int weight[],int n, HaffNode haffTree[])
{
int i,j,m1,m2,x1,x2;
for(i=0;i<2*n-1;i++)
{
if(i<n) haffTree[i].weight=weight[i];
else haffTree[i].weight=0;
haffTree[i].flag=0;
haffTree[i].parent=0;
haffTree[i].leftChild=-1;
haffTree[i].rightChild=-1;
}
//构造哈夫曼树的n-1个非叶子节点
for(i=0;i<n-1;i++)
{
m1=m2=MaxValue;
x1=x2=0;
for(j=0;j<n+i;j++)//find the two maximum weight
{
if(haffTree[j].weight<m1&&haffTree[j].flag==0)
{
m2=m1; x2=x1;
m1=haffTree[j].weight;
x1=j;
}else if(haffTree[j].weight<m2&&haffTree[j].flag==0)
{
m2=haffTree[j].weight;
x2=j;
}
}
//找出的x1,x2是两颗权值最小的子树合并为一颗新的子树
haffTree[x1].parent=n+i;
haffTree[x2].parent=n+i;
haffTree[x1].flag=1;
haffTree[x2].flag=1;
haffTree[n+i].weight=haffTree[x1].weight+haffTree[x2].weight;
haffTree[n+i].leftChild=x1;
haffTree[n+i].rightChild=x2;
}
}
//构造哈夫曼编码
void HaffmanCode(HaffNode haffTree[],int n,Code haffCode[])
{
Code *cd=new Code;
int i,j,child,parent;
//求n个节点的哈夫曼编码
for(i=0;i<n;i++)
{
cd->start=n-1;//编码的最后一位是N-1
cd->weight=haffTree[i].weight;
child=i;
parent=haffTree[child].parent;
while(parent!=0)
{
if(haffTree[parent].leftChild==child)
cd->bit[cd->start]=0;
else cd->bit[cd->start]=1;
cd->start--;
child=parent;
parent=haffTree[child].parent;
}
for(j=cd->start+1;j<n;j++)
haffCode[i].bit[j]=cd->bit[j];
haffCode[i].start=cd->start;
haffCode[i].weight=cd->weight;
}
delete cd;
}
int main()
{
int i,j,n=4;
int weight[]={1,3,5,7};
HaffNode* myHaffTree=new HaffNode[2*n+1];
Code* myHaffCode=new Code[n];
if(n>MaxN)
{
printf("greater than n");
exit(0);
}
Haffman(weight,n, myHaffTree);
HaffmanCode(myHaffTree,n,myHaffCode);
for(i=0;i<n;i++)
{
printf("weight=%d Code=",myHaffCode[i].weight);
for(j=myHaffCode[i].start+1;j<n;j++)
printf("%6d",myHaffCode[i].bit[j]);
printf("\n");
}
delete []myHaffTree;
delete []myHaffCode;
return 0;
}
来源《数据结构》——浙江大学出版社