大家好,今天更新的是哈夫曼树,哈夫曼树又称为最优二叉树
首先还这是要再次感谢 mr.chen 啊,又是他老人家帮我解围了, “三q” 啊!!!
好吧,下面是原滋原味的源代码,如果有错请见谅!!!
// head.h //
#include <iostream>
using namespace std;
typedef struct
{
char data;
int weight;
int lchild, rchild, parent;
}HTNode , *HuffmanTree ;
typedef char **HuffmanCode ;
int Min( HuffmanTree HT, int n ) ///找出权重最小的节点
{
int i, flag;
int f=9999;
for( i=1 ; i<=n; i++ )
{
if( HT[i].weight<f && HT[i].parent==0 )
{
f=HT[i].weight;
flag=i;
}
}
HT[flag].parent=1;
return flag;
}
void Select( HuffmanTree *HT , int n , int *s1, int *s2 )//最小的两个 s1最小 s2次小
{
int x;
*s1=Min(*HT,n);
*s2=Min(*HT,n);
if( (*HT)[*s1].weight > (*HT)[*s2].weight )
{
x=*s1;
*s1=*s2;
*s2=x;
}
}
void HuffmanCoding ( HuffmanTree *HT , HuffmanCode *HC, int n )
{
int m, i, s1, s2, start ;
int c, f ;
HuffmanTree p;
char *cd;
if( n<=1 )
{
return ;
}
m=2*n-1;
*HT=( HuffmanTree ) malloc ( (m+1)*sizeof(HTNode) );
for( p=*HT+1 , i=1 ; i<=n; i++, p++ ) //初始化叶子
{
cout<<"请输入第"<<i<<"个结点的字符信息:";
cin>>(*p).data;
cout<<"该结点的权重:";
cin>>(*p).weight;
(*p).lchild=0;
(*p).parent=0;
(*p).rchild=0;
}
for( ; i<=m; i++, p++ ) //初始化其他结点
{
(*p).parent=0;
}
for( i=n+1 ; i<=m ; ++i )
{
Select(HT,i-1,&s1,&s2);
(*HT)[s1].parent=i;
(*HT)[s2].parent=i;
(*HT)[i].lchild=s1;
(*HT)[i].rchild=s2;
(*HT)[i].weight=(*HT)[s1].weight+(*HT)[s2].weight;
}
//下面求哈夫曼码
*HC = (HuffmanCode) malloc ( (n+1)*sizeof(char*) );
cd=(char *) malloc ( n*sizeof(char) );
cd[n-1]='\0';
for( i=1; i<=n; i++ )
{
start=n-1;
for( c=i, f=(*HT)[i].parent; f!=0; c=f, f=(*HT)[f].parent )
{
if( (*HT)[f].lchild == c )
{
cd[--start]='0';
}
else
{
cd[--start]='1';
}
}
(*HC)[i]=(char *) malloc ( (n-start)*sizeof(char) );
strcpy( (*HC)[i] , &cd[start] );
}
free(cd);
}
main.cpp ///
#include "head.h"
int Min( HuffmanTree HT, int n );
void Select( HuffmanTree *HT , int n , int *s1, int *s2 );
void HuffmanCoding ( HuffmanTree *HT , HuffmanCode *HC, int n );
void main()
{
HuffmanTree HT;
HuffmanCode HC;
HuffmanCoding(&HT,&HC,3);
for( int i=1; i<=3; i++ )
{
cout<<HT[i].data<<" : "<<HC[i]<<endl;
}
}
可能上面的代码不是最好的(当然不是最好的),不过勉强还是把哈夫曼树和哈夫曼编码做出来了。