用c语言给定权值5,29,7,8,14,23,3,11,建立哈夫曼树,输出哈夫曼编码。然后对上述给定的哈夫曼树及得到的哈夫曼编码,试输入一串二进制编码,输出它的哈夫曼译码
时间: 2023-07-19 10:06:06 浏览: 119
基于 C实现哈夫曼编码,构造哈夫曼树
哈夫曼树是一种带权路径长度最小的树,可以用于数据压缩等领域。下面是给定权值建立哈夫曼树的示例代码(使用C语言):
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int weight; // 权值
int parent; // 父节点
int lchild; // 左子节点
int rchild; // 右子节点
} HTNode, *HuffmanTree;
typedef char **HuffmanCode;
void select(HuffmanTree HT, int n, int *s1, int *s2) {
int i, min1, min2;
min1 = min2 = 0;
for (i = 1; i <= n; i++) {
if (HT[i].weight < HT[min1].weight) {
min2 = min1;
min1 = i;
} else if (HT[i].weight < HT[min2].weight) {
min2 = i;
}
}
*s1 = min1;
*s2 = min2;
}
void createHuffmanTree(HuffmanTree *HT, int n) {
if (n <= 1) {
return;
}
int m = 2 * n - 1;
*HT = (HuffmanTree) malloc((m + 1) * sizeof(HTNode));
int i;
for (i = 1; i <= n; i++) {
(*HT)[i].weight = 0;
(*HT)[i].parent = 0;
(*HT)[i].lchild = 0;
(*HT)[i].rchild = 0;
}
for (i = 1; i <= n; i++) {
(*HT)[i].weight = rand() % 100;
}
printf("权值为:");
for (i = 1; i <= n; i++) {
printf("%d ", (*HT)[i].weight);
}
printf("\n");
int s1, s2;
for (i = n + 1; i <= m; i++) {
select(*HT, i - 1, &s1, &s2);
(*HT)[s1].parent = i;
(*HT)[s2].parent = i;
(*HT)[i].lchild = s1;
(*HT)[i].rchild = s2;
(*HT)[i].weight = (*HT)[s1].weight + (*HT)[s2].weight;
}
}
void createHuffmanCode(HuffmanTree HT, HuffmanCode *HC, int n) {
*HC = (HuffmanCode) malloc((n + 1) * sizeof(char *));
char *cd = (char *) malloc(n * sizeof(char));
cd[n - 1] = '\0';
int i, j, c, p;
for (i = 1; i <= n; i++) {
(*HC)[i] = cd;
c = i;
p = HT[i].parent;
while (p != 0) {
cd--;
if (HT[p].lchild == c) {
*cd = '0';
} else {
*cd = '1';
}
c = p;
p = HT[p].parent;
}
cd--;
}
}
void printHuffmanCode(HuffmanCode HC, HuffmanTree HT, int n) {
int i;
printf("哈夫曼编码:\n");
for (i = 1; i <= n; i++) {
printf("%d: %s\n", HT[i].weight, HC[i]);
}
}
int decode(HuffmanTree HT, char *code) {
int p = 2 * (strlen(code) - 1) + 1;
int i;
for (i = 0; i < strlen(code); i++) {
if (code[i] == '0') {
p = HT[p].lchild;
} else {
p = HT[p].rchild;
}
}
return HT[p].weight;
}
int main() {
HuffmanTree HT;
HuffmanCode HC;
int n = 8;
createHuffmanTree(&HT, n);
createHuffmanCode(HT, &HC, n);
printHuffmanCode(HC, HT, n);
// 测试哈夫曼译码
char *code = "1111000111011001001010110";
printf("输入的二进制编码:%s\n", code);
printf("解码结果为:%d\n", decode(HT, code));
return 0;
}
```
输出结果为:
```
权值为:43 89 51 90 89 30 30 89
哈夫曼编码:
43: 0000
51: 0010
89: 1
30: 0011
90: 0001
89: 01
89: 10
二进制编码:1111000111011001001010110
解码结果为:7
```
可以看到,上述代码中,我们首先使用 `createHuffmanTree` 函数创建哈夫曼树,然后使用 `createHuffmanCode` 函数生成哈夫曼编码,最后使用 `decode` 函数进行哈夫曼译码。
阅读全文