数据结构学习-二叉树的基本运算
2016-06-13 19:28
447 查看
问题描述:
构造一棵哈夫曼树,输出对应的哈夫曼编码和平均查找长度。并用表7.8所示的数据进行验证。表7.8 单词及出现的频度
单词 | The | of | a | to | and | in | that | he | is | at | on | for | His | are | be |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
出现频度 | 1192 | 677 | 541 | 518 | 462 | 450 | 242 | 195 | 190 | 181 | 174 | 157 | 138 | 124 | 123 |
代码:
#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; }
运行结果:
相关文章推荐
- 数据结构(线段树):CodeForces 85D Sum of Medians
- web服务器之mongoose:数据结构
- python 的数据结构
- 数据结构中的堆
- 大话数据结构——树
- 数据结构与算法:链表
- 数据结构--哈夫曼树
- 数据结构 单链表逆序
- 数据结构—哈夫曼编码应用
- 数据结构(LCT动态树):BZOJ 1036: [ZJOI2008]树的统计Count
- 0-1背包问题与数组分割问题
- Nginx 基础数据结构
- 数据结构(线段树):BZOJ 1568 [JSOI2008]Blue Mary开公司
- 数据结构第七次试验
- 数据结构(线段树):SPOJ GSS3 - Can you answer these queries III
- thrift数据结构
- 数据结构算法模拟系统
- 多余元素删除之移位算法
- UVA - 1395 - Slim Span(Kruskal算法+枚举)
- 数据结构之二叉树