对于Huffman树最终该输出什么不清楚
#include<stdio.h> #include<stdlib.h> #define leafNumber 20 //默认权值集合大小 #define totalNumber 39 //数结点个数=2*leafNumber-1 typedef struct { char data; //结点的值 int weight; //结点的权 int Parent,lchild,rchild; //双亲、左、右子女结点指针 }HTNode; typedef struct { HTNode elem[totalNumber]; //Huffman树存储数组 int num,root; //num是外结点数,root是根 }HFTree; //算法 void createHFTree (HFTree &HT,char value[],int fr[],int n){ //输入数据value[n]和相应权值fr[n],构造用三叉链表表示的Huffman树HT int i,k,s1,s2; int min1,min2,maxWeight; for(i = 0;i<n;i++){ //所有外结点赋值 HT.elem[i].data=value[i]; HT.elem[i].weight=fr[i]; } for(int i= 0;i<n;i++){ if(HT.elem[i].weight>HT.elem[i+1].weight){ maxWeight = HT.elem[i].weight; }else maxWeight = HT.elem[i+1].weight; } for(i = 0;i<leafNumber;i++) //所有指针置空 HT.elem[i].Parent = HT.elem[i].lchild = HT.elem[i].rchild = -1; for(i = n;i<2*n-1;i++){ //逐步构造Huffman树 min1 = min2 = maxWeight; //min1是最小值,min2是次小值 s1 = s2 = 0; //s1是最小值点,s2是次小值点 for(k = 0;k<i;k++) //构造Huffman树的过程 if(HT.elem[k].Parent == -1) //未成为其他树的子树 if(HT.elem[k].weight<min1){ //新的最小值 min2 = min1; s2 = s1; //原来的最小值变成次小值 min1 = HT.elem[k].weight; //记忆新的最小值 s1 = k; }else if(HT.elem[k].weight<min2){ //新的次小值 min2 = HT.elem[k].weight; s2 = k; } HT.elem[s1].Parent=HT.elem[s2].Parent=i; //构造子树 HT.elem[i].lchild=s1; HT.elem[i].rchild=s2; HT.elem[i].weight=HT.elem[s1].weight+HT.elem[s2].weight; } HT.num=n; HT.root=2*n-2; } //输出Huffman树 void printMessage(HFTree &HT,char value[],int fr[],int n){ for(int i = 0;i<n;i++){ printf("%d\t",value[i]); printf("%d\t",fr[i]); printf("\n"); } } main(){ HFTree HT; int n,b[n]; //所需要的数据个数 printf("请输入需要编码的字符个数:"); scanf("%d",&n); char a[n]; for(int i = 0;i<n;i++){ printf("请输入第%d位数据:",i+1); scanf("%d",&a[i]); } for(int i = 0;i<n;i++){ printf("请输入第%d位权值的数据:",i+1); scanf("%d",&b[i]); } createHFTree(HT,a,b,n); printMessage(HT,a,b,n); }
原文地址:https://www.cnblogs.com/lvzhiqi/p/11001327.html
时间: 2024-10-09 13:12:27