您的位置:首页 > 理论基础 > 数据结构算法

数据结构学习-二叉树的基本运算

2016-06-13 19:28 447 查看

问题描述:

构造一棵哈夫曼树,输出对应的哈夫曼编码和平均查找长度。并用表7.8所示的数据进行验证。

表7.8 单词及出现的频度

单词TheofatoandinthatheisatonforHisarebe
出现频度1192677541518462450242195190181174157138124123

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int n=15;
typedef struct
{
char data[5];
double weight;
int parent;
int lchild;
int rchild;
}HTNode;
typedef struct
{
char cd
;
int start;
}HCode;

void CreateHT(HTNode ht[])
{
int i,k,lnode,rnode;
double min1,min2;
for(i=0;i<2*n-1;i++)
ht[i].lchild=ht[i].rchild=ht[i].parent=-1;
for(i=n;i<2*n-1;i++)
{
min1=min2=9999;
lnode=rnode=-1;
for(k=0;k<i;k++)
{
if(ht[k].parent==-1)
{
if(ht[k].weight<min1)
{
min2=min1;rnode=lnode;
min1=ht[k].weight;lnode=k;
}
else if(ht[k].weight<min2)
{
min2=ht[k].weight;rnode=k;
}
}
}
ht[i].weight=ht[lnode].weight+ht[rnode].weight;
ht[i].lchild=lnode;ht[i].rchild=rnode;
ht[lnode].parent=i;ht[rnode].parent=i;
}
}
void CreatHCode(HTNode ht[],HCode hcd[])
{
int i,f,c;
HCode hc;
for(i=0;i<n;i++)
{
hc.start=n;
c=i;
f=ht[i].parent;
while(f!=-1)
{
if(ht[f].lchild==c)
hc.cd[--hc.start]='0';
else
hc.cd[--hc.start]='1';
c=f;f=ht[f].parent;
}
hcd[i]=hc;
}
}
void DispHCode(HTNode ht[],HCode hc[])
{
int i,j,k;
double sum=0,m=0;
cout<<"输出哈弗曼编码:\n";
for(i=0;i<n;i++)
{
j=0;
cout<<"\t"<<ht[i].data<<":\t";
for(k=hc[i].start;k<n;k++)
{
cout<<hc[i].cd[k];
j++;
}
cout<<endl;
m+=ht[i].weight;
sum+=ht[i].weight*j;
}
cout<<"平均长度="<<sum/m<<endl;
}
int main()
{
int w[]={1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123};
char *str[]={"The","of","a","to","and","in","that","he","is","at","on","for","His","are","be"};
HTNode ht[2*n-1];
HCode hc
;
for(int i=0;i<n;i++)
{
strcpy(ht[i].data,str[i]);
ht[i].weight=w[i];
}
CreateHT(ht);
CreatHCode(ht,hc);
DispHCode(ht,hc);
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: