哈夫曼树的构造c语言代码
时间: 2023-07-09 14:24:01 浏览: 88
下面是一个简单的哈夫曼树构造的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODE_NUM 1000
#define MAX_CODE_LEN 100
typedef struct TreeNode {
char data;
int weight;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
void huffman_encoding(TreeNode *root, char *code, int len) {
static char code_table[MAX_NODE_NUM][MAX_CODE_LEN];
if (root->left == NULL && root->right == NULL) {
strncpy(code_table[root->data], code, len);
code_table[root->data][len] = '\0';
return;
}
code[len] = '0';
huffman_encoding(root->left, code, len+1);
code[len] = '1';
huffman_encoding(root->right, code, len+1);
}
void huffman_tree(TreeNode **root, char *str) {
int count[256] = {0};
for (int i=0; i<strlen(str); i++) {
count[(int)str[i]]++;
}
struct {
int weight;
TreeNode *node;
} nodes[MAX_NODE_NUM];
int node_num = 0;
for (int i=0; i<256; i++) {
if (count[i] > 0) {
nodes[node_num].node = (TreeNode *)malloc(sizeof(TreeNode));
nodes[node_num].node->data = i;
nodes[node_num].node->weight = count[i];
nodes[node_num].node->left = NULL;
nodes[node_num].node->right = NULL;
nodes[node_num].weight = count[i];
node_num++;
}
}
while (node_num > 1) {
int min1 = 0, min2 = 1;
if (nodes[min1].weight > nodes[min2].weight) {
int tmp = min1;
min1 = min2;
min2 = tmp;
}
for (int i=2; i<node_num; i++) {
if (nodes[i].weight < nodes[min1].weight) {
min2 = min1;
min1 = i;
} else if (nodes[i].weight < nodes[min2].weight) {
min2 = i;
}
}
TreeNode *new_node = (TreeNode *)malloc(sizeof(TreeNode));
new_node->data = '\0';
new_node->weight = nodes[min1].weight + nodes[min2].weight;
new_node->left = nodes[min1].node;
new_node->right = nodes[min2].node;
nodes[min1].node = new_node;
nodes[min1].weight = new_node->weight;
nodes[min2] = nodes[node_num-1];
node_num--;
}
*root = nodes[0].node;
}
int main() {
char str[] = "hello world";
TreeNode *root;
huffman_tree(&root, str);
char code[MAX_CODE_LEN];
huffman_encoding(root, code, 0);
for (int i=0; i<256; i++) {
if (strlen(code_table[i]) > 0) {
printf("%c: %s\n", (char)i, code_table[i]);
}
}
return 0;
}
```
该代码将一个字符串进行哈夫曼树编码,并输出每个字符的编码结果。
阅读全文