c语言给定n个叶子结点和权值,建立哈夫曼树并输出。
时间: 2024-01-22 21:17:54 浏览: 85
以下是使用C语言实现建立哈夫曼树并输出的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEAF_NODES 100
// 结点结构体
typedef struct Node {
int weight; // 权值
int parent, left, right;// 父结点,左子结点,右子结点的下标
} Node;
// 获取权值最小的两个结点的下标
void getTwoMinNodes(Node *nodes, int n, int *min1, int *min2) {
int i;
*min1 = *min2 = -1;
for (i = 0; i < n; i++) {
if (nodes[i].parent == -1) {
if (*min1 == -1 || nodes[i].weight < nodes[*min1].weight) {
*min2 = *min1;
*min1 = i;
} else if (*min2 == -1 || nodes[i].weight < nodes[*min2].weight) {
*min2 = i;
}
}
}
}
// 构建哈夫曼树
void buildHuffmanTree(Node *nodes, int n) {
int i, min1, min2;
for (i = n; i < 2 * n - 1; i++) {
getTwoMinNodes(nodes, i, &min1, &min2);
nodes[min1].parent = i;
nodes[min2].parent = i;
nodes[i].left = min1;
nodes[i].right = min2;
nodes[i].weight = nodes[min1].weight + nodes[min2].weight;
}
}
// 输出哈夫曼编码
void printHuffmanCode(Node *nodes, int n) {
int i, j, parent, cur;
char *code = (char *) malloc(n * sizeof(char));
for (i = 0; i < n; i++) {
printf("Leaf Node %d: weight=%d, code=", i, nodes[i].weight);
parent = nodes[i].parent;
cur = i;
j = 0;
while (parent != -1) {
if (nodes[parent].left == cur) {
code[j++] = '0';
} else {
code[j++] = '1';
}
cur = parent;
parent = nodes[cur].parent;
}
while (j > 0) {
printf("%c", code[--j]);
}
printf("\n");
}
free(code);
}
int main() {
int n, i;
Node nodes[MAX_LEAF_NODES * 2 - 1];
printf("Enter the number of leaf nodes: ");
scanf("%d", &n);
printf("Enter the weight of each leaf node:\n");
for (i = 0; i < n; i++) {
scanf("%d", &nodes[i].weight);
nodes[i].parent = -1;
nodes[i].left = -1;
nodes[i].right = -1;
}
buildHuffmanTree(nodes, n);
printHuffmanCode(nodes, n);
return 0;
}
```
输入格式为先输入叶子结点的数量,再输入每个叶子结点的权值,例如:
```
Enter the number of leaf nodes: 5
Enter the weight of each leaf node:
2 3 7 8 10
```
输出格式为每个叶子结点的权值和哈夫曼编码,例如:
```
Leaf Node 0: weight=2, code=1111
Leaf Node 1: weight=3, code=1110
Leaf Node 2: weight=7, code=110
Leaf Node 3: weight=8, code=10
Leaf Node 4: weight=10, code=0
```
阅读全文