#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define n 6 //叶子数目
#define m 2*n-1 //节点总数
#define Maxval 1 //最大权值
//定义结构体类型
typedef char datatype;
typedef struct{
float weight; //权值
datatype data; //数据
int lchild, rchild, parent; //左右子树的下标和父节点的下标
} hufmtree;
hufmtree tree[m]; //定义哈夫曼树节点数组
//定义编码结构体,表示每个叶子节点的哈夫曼编码
typedef struct{
char bits[n]; //编码数组位串,其中n为叶子节点数目
int start; //编码在位串的起始位置
datatype data; //数据
} codetype;
codetype code[n]; //定义编码数组
//HUFFMAN函数用于构建哈夫曼树
void HUFFMAN(hufmtree tree[]){
int i, j, p1, p2;
char ch;
float small1, small2, f;
for (i = 0; i < m; i++) { //初始化
tree[i].parent = 0;
tree[i].rchild = 0;
tree[i].lchild = 0;
tree[i].data = '0';
tree[i].weight = 0.0;
}
for (i = 0; i < n; i++) { //输入n个叶子节点的权值和数据
scanf("%f", &f);
tree[i].weight = f;
scanf(" %c", &ch); //注意空格的处理,避免读入错误字符
tree[i].data = ch;
}
for (i = n; i < m; i++) { //将剩下的非叶子节点初始化
tree[i].parent = 0;
tree[i].rchild = 0;
tree[i].lchild = 0;
tree[i].data = '0';
tree[i].weight = 0.0;
}
for (i = n; i < m; i++) {
p1 = p2 = 0; //每次循环将最小和次小的两个节点下标清零
small1 = small2 = Maxval; //每次循环将最小和次小的权值初始化为最大值
for (j = 0; j <= i - 1; j++) {
if (tree[j].parent == 0) { //只有没有父节点的节点才会被考虑
if (tree[j].weight < small1) {
small2 = small1;
small1 = tree[j].weight;
p2 = p1;
p1 = j;
}
else if (tree[j].weight < small2) {
small2 = tree[j].weight;
p2 = j;
}
}
}
tree[p1].parent = i; //将选择出的两个节点合并成一个新节点i
tree[p2].parent = i;
tree[i].lchild = p1;
tree[i].rchild = p2;
tree[i].weight = tree[p1].weight + tree[p2].weight;
}
}
//HUFFMANCODE函数用于求出哈夫曼编码
void HUFFMANCODE(codetype code[], hufmtree tree[]){
int i, c, p;
codetype cd;
for (i = 0; i < n; i++) { //对每个叶子节点求解哈夫曼编码
cd.start = n;
c = i;
p = tree[c].parent;
cd.data = tree[c].data;
while (p != 0) { //从叶子节点向根节点遍历,求出编码
cd.start--;
if (tree[p].lchild == c) {
cd.bits[cd.start] = '0';
}
else {
cd.bits[cd.start] = '1';
}
c = p;
p = tree[c].parent;
}
code[i] = cd; //保存哈夫曼编码到code数组中
printf("%c", cd.data);
for (int k = cd.start; k < n; k++) {
printf("%c", cd.bits[k]);
}
printf("\n");
}
}
//HUFFMANDECODE函数用于进行哈夫曼解码
void HUFFMANDECODE(codetype code[], hufmtree tree[]){
int i, c, p, b;
int endflag = 2; //输入2表示密码结束
i = m - 1; //从根节点开始逐步往下走
scanf("%d",&b);
while(b != endflag){
if(b == 0) {
i = tree[i].lchild;
}
else {
i = tree[i].rchild;
}
if (tree[i].lchild == 0) { //如果到达了叶子节点,则输出对应的数据,并重新回到根节点
putchar(code[i].data);
i = m - 1;
}
scanf("%d",&b);
}
if ((tree[i].lchild != 0) && (i != m - 1)) { //不是叶子节点,则解码失败
printf("\nERROR\n");
}
}
int main(){
printf("输入结点的权值和结点字母,用空格隔开:(如0.4 a)\n");
HUFFMAN(tree);
printf("\n编码结果\n");
HUFFMANCODE(code, tree);
printf("\n开始译码,请输入密码:\n");
HUFFMANDECODE(code, tree);
printf("\n");
return 0;
}