c语言基于哈夫曼树的数据压缩事例
时间: 2023-12-25 10:29:16 浏览: 107
基于哈夫曼树的数据压缩是一种常见的压缩算法,它通过构建哈夫曼树来实现数据的压缩和解压缩。下面是一个C语言的基于哈夫曼树的数据压缩的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义哈夫曼树节点结构体
typedef struct HuffmanNode {
int data; // 数据
int weight; // 权重
struct HuffmanNode *left; // 左子节点
struct HuffmanNode *right; // 右子节点
} HuffmanNode;
// 创建哈夫曼树
HuffmanNode* createHuffmanTree(int data[], int weight[], int n) {
HuffmanNode **nodes;
nodes = (HuffmanNode**)malloc(sizeof(HuffmanNode*) * n);
for (int i = 0; i < n; i++) {
nodes[i] = (HuffmanNode*)malloc(sizeof(HuffmanNode));
nodes[i]->data = data[i];
nodes[i]->weight = weight[i];
nodes[i]->left = NULL;
nodes[i]->right = NULL;
}
while (n > 1) {
int min1 = 0, min2 = 1;
for (int i = 0; i < n; i++) {
if (nodes[i]->weight < nodes[min1]->weight) {
min2 = min1;
min1 = i;
} else if (nodes[i]->weight < nodes[min2]->weight) {
min2 = i;
}
}
HuffmanNode *newNode = (HuffmanNode*)malloc(sizeof(HuffmanNode));
newNode->data = -1;
newNode->weight = nodes[min1]->weight + nodes[min2]->weight;
newNode->left = nodes[min1];
newNode->right = nodes[min2];
nodes[min1] = newNode;
nodes[min2] = nodes[n - 1];
n--;
}
return nodes[0];
}
// 哈夫曼编码
void huffmanEncoding(HuffmanNode *root, int code[], int depth) {
if (root == NULL) {
return;
}
if (root->data != -1) {
printf("%d: ", root->data);
for (int i = 0; i < depth; i++) {
printf("%d", code[i]);
}
printf("\n");
}
code[depth] = 0;
huffmanEncoding(root->left, code, depth + 1);
code[depth] = 1;
huffmanEncoding(root->right, code, depth + 1);
}
int main() {
int data[] = {1, 2, 3, 4, 5};
int weight[] = {5, 4, 3, 2, 1};
int n = sizeof(data) / sizeof(data[0]);
HuffmanNode *root = createHuffmanTree(data, weight, n);
int code[100];
huffmanEncoding(root, code, 0);
return 0;
}
```
这个示例中,我们首先定义了一个哈夫曼树节点的结构体,然后通过`createHuffmanTree`函数创建哈夫曼树。接下来,我们使用`huffmanEncoding`函数对哈夫曼树进行编码,输出每个节点的编码结果。
阅读全文