什么是哈夫曼树呢?

[复制链接]
查看11 | 回复1 | 2019-12-11 03:36:10 | 显示全部楼层 |阅读模式
#include #include #include #includea #include #define MAXVALUE 200 /*权值的最大值*/ #define MAXBIT 30 /*最大的编码位数*/ #define MAXNODE 30 /*初始的最大的结点数*/ struct haffnode {char data; int weight; int flag; int parent; /*双亲结点的下标*/ int leftchild; /*左孩子下标*/ int rightchild; /*右孩子下标*/ }; struct haffcode {int bit[MAXNODE]; int start; /*编码的起始下标*/ char data; int weight; /*字符权值*/ }; /*函数说明*/ /************************************************************************/ void pprintf(struct haffcode haffcode[],int n); /*输出函数*/ void haffmantree(int weight[],int n,struct haffnode hafftree[],char data[]); /*建立哈夫曼树*/ void haffmancode(struct haffnode hafftree[],int n,struct haffcode haffcode[]); /*求哈夫曼编码*/ void test(struct haffcode haffcode[],int n); /*测试函数*/ void end(); /*结束界面函数*/ /************************************************************************/ void haffmantree(int weight[],int n,struct haffnode hafftree[],char data[]) /*建立叶结点个数为n,权值数组为weight[]的哈夫曼树*/ {int i,j,m1,m2,x1,x2; /*哈夫曼树hafftree[]初始化,n个叶结点共有2n-1个结点*/ for(i=0;istart=MAXBIT-1; /*不等长编码的最后一位是n-1*/ cd->weight=hafftree.weight; cd->data=hafftree.data; /*取得编码对应值的字符*/ child=i; parent=hafftree[child].parent; while(parent!=0) {if(hafftree[parent].leftchild==child) cd->bit[cd->start]=0; /*左孩子编码为0*/ else cd->bit[cd->start]=1; /*右孩子编码为1*/ cd->start--; child=parent; parent=hafftree[child].parent; } for(j=cd->start+1;jbit[j]; haffcode.data=cd->data; haffcode.start=cd->start; haffcode.weight=cd->weight; } } void pprintf(struct haffcode myhaffcode[],int n) {int i,j,count=0; clrscr(); for(i=0;i=MAXNODE) {printf("you input the data number >=MAXNODE."); exit(1); } for(i=0;iMAXNODE-1) {printf("在系统中找不到与第个%d字符相匹配的编码\n",i+1); continue; } newhaffcode.start=haffcode[k].start; newhaffcode.weight=haffcode[k].weight; newhaffcode.data=haffcode[k].data; for(s=haffcode[k].start+1;sMAXNODE) {printf("you input the haffnode > MAXNODE,so you input the data is wrong"); printf("\n"); exit(1); } clrscr(); textcolor(YELLOW); cprintf("WELCOME!这是一个求哈夫曼编码的问题"); printf("\n"); cprintf("即对所有的字母进行编码后,在根据用户的需要,对用户的要求进行编码。"); printf("\n"); cprintf("注意:本程序只支持小写字母,空格用大写字母T代替! "); printf("\n"); getch(); textcolor(YELLOW); cprintf("Ready?Enter,if you want to begin!\n"); printf("\n"); getch(); cprintf("Now,开始演示哈夫曼编码."); getch(); haffmantree(weight,n,myhafftree,data); haffmancode(myhafftree,n,myhaffcode); pprintf(myhaffcode,n); clrscr(); printf("若执行自定义编译,请输入y继续。否则程序将结束."); if((ch=getch())=='y'||ch=='Y') test(myhaffcode,n); getch(); clrscr(); end(); getch(); exit(1); }
回复

使用道具 举报

千问 | 2019-12-11 03:36:10 | 显示全部楼层
夫曼树是带权路径长度最小的二叉树,用途是平均查找信息的代价最小。 普通二叉树的用途也普通,比较通用,就是信息存储和查找。 普通二叉树可能有的只有一个子节点,而哈夫曼树一定有两个。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行