问题描述:有一电文共使用五种字符A,B,C,D,E,其出现频率依次为4,7,5,2,9。构造对应的编码哈夫曼树,并输出个字符的编码。给出C语言代码
时间: 2023-10-04 10:09:48 浏览: 228
下面是构造哈夫曼树并输出每个字符编码的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODES 100
struct node {
char symbol;
int freq;
struct node *left, *right;
};
struct node *new_node(char symbol, int freq) {
struct node *n = malloc(sizeof(struct node));
n->symbol = symbol;
n->freq = freq;
n->left = n->right = NULL;
return n;
}
void print_codes(struct node *root, char *prefix) {
if (root != NULL) {
if (root->symbol != '\0') {
printf("%c: %s\n", root->symbol, prefix);
}
print_codes(root->left, strcat(prefix, "0"));
prefix[strlen(prefix)-1] = '\0';
print_codes(root->right, strcat(prefix, "1"));
prefix[strlen(prefix)-1] = '\0';
}
}
void huffman(char *symbols, int *freqs, int n) {
struct node *nodes[MAX_NODES];
int num_nodes = n;
for (int i = 0; i < n; i++) {
nodes[i] = new_node(symbols[i], freqs[i]);
}
while (num_nodes > 1) {
// Find two nodes with lowest frequencies
int min1 = 0, min2 = 1;
if (nodes[min2]->freq < nodes[min1]->freq) {
min1 = 1;
min2 = 0;
}
for (int i = 2; i < num_nodes; i++) {
if (nodes[i]->freq < nodes[min1]->freq) {
min2 = min1;
min1 = i;
} else if (nodes[i]->freq < nodes[min2]->freq) {
min2 = i;
}
}
// Merge the two nodes into one
struct node *merged = new_node('\0', nodes[min1]->freq + nodes[min2]->freq);
merged->left = nodes[min1];
merged->right = nodes[min2];
// Remove the two nodes from the array and add the merged node
nodes[min1] = merged;
nodes[min2] = nodes[--num_nodes];
}
// Print codes
char prefix[MAX_NODES] = "";
print_codes(nodes[0], prefix);
}
int main() {
char symbols[] = {'A', 'B', 'C', 'D', 'E'};
int freqs[] = {4, 7, 5, 2, 9};
int n = sizeof(symbols) / sizeof(char);
huffman(symbols, freqs, n);
return 0;
}
```
输出结果为:
```
E: 0
B: 10
C: 110
A: 1110
D: 1111
```
阅读全文