给定一组结点及对应的权值,创建一棵哈夫曼树,输出每个结点的哈夫曼编码,和整棵树的WPL值。用c语言实现
时间: 2024-05-14 12:16:29 浏览: 99
以下是C语言实现哈夫曼树的代码,其中包括创建哈夫曼树、输出哈夫曼编码和计算WPL值的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODE_NUM 100
// 定义哈夫曼树的结点结构体
struct HuffmanNode {
int weight; // 权值
int parent, lchild, rchild; // 父亲结点、左孩子结点、右孩子结点的下标
char code[MAX_NODE_NUM]; // 存储哈夫曼编码
};
// 创建哈夫曼树并返回根结点下标
int CreateHuffmanTree(struct HuffmanNode *huffmanTree, int n) {
int i, j, x1, x2, m1, m2;
for (i = 0; i < 2 * n - 1; i++) {
huffmanTree[i].parent = huffmanTree[i].lchild = huffmanTree[i].rchild = -1;
}
for (i = 0; i < n; i++) {
printf("请输入第%d个结点的权值:", i + 1);
scanf("%d", &huffmanTree[i].weight);
}
for (i = 0; i < n - 1; i++) {
m1 = m2 = 10000; // 找出最小的两个结点
x1 = x2 = -1;
for (j = 0; j < n + i; j++) {
if (huffmanTree[j].weight < m1 && huffmanTree[j].parent == -1) {
m2 = m1;
x2 = x1;
m1 = huffmanTree[j].weight;
x1 = j;
} else if (huffmanTree[j].weight < m2 && huffmanTree[j].parent == -1) {
m2 = huffmanTree[j].weight;
x2 = j;
}
}
huffmanTree[x1].parent = n + i;
huffmanTree[x2].parent = n + i;
huffmanTree[n + i].weight = huffmanTree[x1].weight + huffmanTree[x2].weight;
huffmanTree[n + i].lchild = x1;
huffmanTree[n + i].rchild = x2;
}
return n * 2 - 2;
}
// 输出哈夫曼编码
void PrintHuffmanCode(struct HuffmanNode *huffmanTree, int n) {
int i, j, child, parent;
for (i = 0; i < n; i++) {
child = i;
parent = huffmanTree[child].parent;
while (parent != -1) {
if (huffmanTree[parent].lchild == child) {
strcat(huffmanTree[i].code, "0");
} else {
strcat(huffmanTree[i].code, "1");
}
child = parent;
parent = huffmanTree[child].parent;
}
printf("结点%d的哈夫曼编码为:%s\n", i + 1, strrev(huffmanTree[i].code));
}
}
// 计算WPL值
int CalculateWpl(struct HuffmanNode *huffmanTree, int n) {
int i, wpl = 0;
for (i = 0; i < n; i++) {
wpl += huffmanTree[i].weight * strlen(huffmanTree[i].code);
}
return wpl;
}
int main() {
struct HuffmanNode huffmanTree[MAX_NODE_NUM];
int n, root;
printf("请输入结点个数:");
scanf("%d", &n);
root = CreateHuffmanTree(huffmanTree, n);
printf("哈夫曼树创建成功!\n");
PrintHuffmanCode(huffmanTree, n);
printf("哈夫曼树的WPL值为:%d\n", CalculateWpl(huffmanTree, n));
return 0;
}
```
以上代码实现了哈夫曼树的创建、输出哈夫曼编码和计算WPL值的功能。其中,CreateHuffmanTree函数用于创建哈夫曼树,返回根结点下标;PrintHuffmanCode函数用于输出每个结点的哈夫曼编码;CalculateWpl函数用于计算整棵树的WPL值。
阅读全文