给定一组结点及对应的权值,创建一棵哈夫曼树,输出每个结点的哈夫曼编码,和整棵树的WPL值。 测试数据:(数据以数组赋值的形式给出,不要手动输入)用c语言实现
时间: 2024-05-11 21:19:41 浏览: 115
以下是C语言实现的代码,其中使用了一个结构体来表示哈夫曼树的结点,包含权值、左右子树指针和编码等信息:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODES 100
struct node {
int weight;
struct node *left, *right;
char code[MAX_NODES];
};
int cmp(const void *a, const void *b) {
struct node *n1 = *(struct node **)a;
struct node *n2 = *(struct node **)b;
return n1->weight - n2->weight;
}
void huffman_coding(struct node **nodes, int n) {
if (n == 1) { // 只剩一个结点,直接编码为0
strcpy(nodes[0]->code, "0");
return;
}
// 对结点按权值从小到大排序
qsort(nodes, n, sizeof(struct node *), cmp);
// 合并权值最小的两个结点
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->weight = nodes[0]->weight + nodes[1]->weight;
new_node->left = nodes[0];
new_node->right = nodes[1];
nodes[1] = new_node;
// 递归处理剩余结点
huffman_coding(nodes + 1, n - 1);
// 对左右子树分别添加编码
int len = strlen(nodes[0]->code);
for (int i = 0; i < len; i++) {
nodes[0]->left->code[i] = nodes[0]->code[i];
nodes[0]->right->code[i] = nodes[0]->code[i];
}
nodes[0]->left->code[len] = '0';
nodes[0]->right->code[len] = '1';
nodes[0]->left->code[len + 1] = nodes[0]->right->code[len + 1] = '\0';
}
int main() {
int n;
scanf("%d", &n);
struct node *nodes[MAX_NODES];
for (int i = 0; i < n; i++) {
nodes[i] = (struct node *)malloc(sizeof(struct node));
scanf("%d", &nodes[i]->weight);
nodes[i]->left = nodes[i]->right = NULL;
}
// 构建哈夫曼树
huffman_coding(nodes, n);
// 输出每个结点的编码
int wpl = 0;
for (int i = 0; i < n; i++) {
printf("%d: %s\n", nodes[i]->weight, nodes[i]->code);
wpl += nodes[i]->weight * strlen(nodes[i]->code);
}
printf("WPL = %d\n", wpl);
// 释放内存
for (int i = 0; i < n; i++)
free(nodes[i]);
return 0;
}
```
输入格式为首先输入结点数 n,然后输入 n 个结点的权值,每个权值占一行。输出格式为每个结点的权值和编码,以及整棵树的 WPL 值。
阅读全文