用c语言编写哈夫曼树解码的代码并在main函数中实现输出解码后的结果
时间: 2024-03-05 13:51:57 浏览: 61
好的,以下是用C语言编写哈夫曼树解码的代码,并在main函数中实现输出解码后的结果的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TREE_NODE 1000
// 哈夫曼树节点结构体
typedef struct huffman_node {
char data;
int weight;
int parent;
int left_child;
int right_child;
} HuffmanNode;
// 哈夫曼树结构体
typedef struct huffman_tree {
HuffmanNode nodes[MAX_TREE_NODE];
int node_count;
} HuffmanTree;
// 构建哈夫曼树
void build_huffman_tree(HuffmanTree* tree, char* data, int* weights, int count) {
// 初始化节点
for (int i = 0; i < count; i++) {
tree->nodes[i].data = data[i];
tree->nodes[i].weight = weights[i];
tree->nodes[i].parent = -1;
tree->nodes[i].left_child = -1;
tree->nodes[i].right_child = -1;
}
tree->node_count = count;
// 构建哈夫曼树
for (int i = count; i < MAX_TREE_NODE; i++) {
tree->nodes[i].data = '\0';
tree->nodes[i].weight = 0;
tree->nodes[i].parent = -1;
tree->nodes[i].left_child = -1;
tree->nodes[i].right_child = -1;
}
for (int i = count; i < 2 * count - 1; i++) {
int left_child = -1;
int right_child = -1;
int min_weight = INT_MAX;
for (int j = 0; j < i; j++) {
if (tree->nodes[j].parent == -1) {
if (tree->nodes[j].weight < min_weight) {
right_child = left_child;
left_child = j;
min_weight = tree->nodes[j].weight;
}
else if (tree->nodes[j].weight == min_weight) {
right_child = j;
}
}
}
tree->nodes[left_child].parent = i;
tree->nodes[right_child].parent = i;
tree->nodes[i].left_child = left_child;
tree->nodes[i].right_child = right_child;
tree->nodes[i].weight = tree->nodes[left_child].weight + tree->nodes[right_child].weight;
}
}
// 哈夫曼树解码
void huffman_decode(HuffmanTree* tree, char* encoded_data, char* decoded_data) {
int i = 0;
int j = 0;
int current_node = 2 * tree->node_count - 2;
while (encoded_data[i] != '\0') {
if (encoded_data[i] == '0') {
current_node = tree->nodes[current_node].left_child;
}
else if (encoded_data[i] == '1') {
current_node = tree->nodes[current_node].right_child;
}
if (tree->nodes[current_node].left_child == -1 && tree->nodes[current_node].right_child == -1) {
decoded_data[j] = tree->nodes[current_node].data;
j++;
current_node = 2 * tree->node_count - 2;
}
i++;
}
decoded_data[j] = '\0';
}
int main() {
// 假设编码为:"0010101111011110101"
char encoded_data[] = "0010101111011110101";
// 假设字符和权重分别为:{'a', 'b', 'c', 'd', 'e'} 和 {5, 7, 2, 8, 4}
char data[] = {'a', 'b', 'c', 'd', 'e'};
int weights[] = {5, 7, 2, 8, 4};
int count = sizeof(data) / sizeof(data[0]);
// 构建哈夫曼树
HuffmanTree tree;
build_huffman_tree(&tree, data, weights, count);
// 解码
char decoded_data[MAX_TREE_NODE];
memset(decoded_data, 0, sizeof(decoded_data));
huffman_decode(&tree, encoded_data, decoded_data);
// 输出解码后的结果
printf("Decoded data: %s\n", decoded_data);
return 0;
}
```
在上述示例中,我们假设编码为:"0010101111011110101",字符和权重分别为:{'a', 'b', 'c', 'd', 'e'} 和 {5, 7, 2, 8, 4},然后构建哈夫曼树并解码,最后输出解码后的结果。
阅读全文