构造赫夫曼编码进行通信c语言代码
时间: 2024-12-24 13:21:28 浏览: 9
赫夫曼编码是一种用于数据压缩的无损数据编码技术,尤其适合于那些频繁出现某些字符而其他字符较少的情况。在C语言中,我们可以创建一个简单的赫夫曼树生成算法,并用于构建编码表。下面是一个基本的示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char data;
int freq;
struct Node *left, *right;
} Node;
Node* create newNode(char data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->freq = 1;
node->left = node->right = NULL;
return node;
}
void insert(Node** root, char data) {
if (*root == NULL) {
*root = createNewNode(data);
} else if (data <= (*root)->data) {
insert(&((*root)->left), data);
} else {
insert(&((*root)->right), data);
}
}
Node* buildHuffmanTree(Node** root) {
if (*root == NULL || (*root)->left == NULL && (*root)->right == NULL)
return *root;
Node* left = buildHuffmanTree(&(*root)->left);
Node* right = buildHuffmanTree(&(*root)->right);
if (left->freq > right->freq) {
right->parent = left;
left->right = right;
} else {
left->parent = right;
right->left = left;
}
return left->freq > right->freq ? left : right;
}
// Generate Huffman codes using the tree
void generateCodes(Node* root, char* code, int len, char output[]) {
if (root == NULL) return;
// Add current character and its code to output array
output[len] = root->data;
code[root->data] = output + len - 1;
// Recursively traverse left and right subtrees
generateCodes(root->left, code, len + 1, output);
generateCodes(root->right, code, len + 1, output);
}
int main() {
Node* root = NULL; // Initialize an empty tree
// Add your characters and their frequencies here
insert(&root, 'a');
insert(&root, 'b'); // ...
// Build the Huffman tree
root = buildHuffmanTree(&root);
// Create a string for encoding
const char input[] = "abracadabra";
char encoded[100];
char* code = generateCodes(root, "", 0, encoded);
printf("Original message: %s\nEncoded message: %s", input, encoded);
return 0;
}
```
这个例子展示了如何从一个字符及其频率数组开始生成赫夫曼树,然后构造编码表。请注意,这只是一个基础版本,实际应用中可能需要添加错误处理、用户输入读取等功能。
阅读全文