.给定n个叶子结点和权值,建立哈夫曼树并输出。C语言
时间: 2024-03-08 10:50:34 浏览: 75
以下是一个简单的C语言实现,基于哈夫曼树的经典算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEAF_NODES 100
typedef struct {
int weight;
int parent;
int lchild;
int rchild;
} HuffNode;
void huffman(int leafNodes[], int n, HuffNode huffTree[]) {
int i, j, min1, min2;
int m = 2 * n - 1;
for (i = 0; i < n; i++) {
huffTree[i].weight = leafNodes[i];
huffTree[i].parent = -1;
huffTree[i].lchild = -1;
huffTree[i].rchild = -1;
}
for (i = n; i < m; i++) {
min1 = min2 = -1;
for (j = 0; j < i; j++) {
if (huffTree[j].parent == -1) {
if (min1 == -1 || huffTree[j].weight < huffTree[min1].weight) {
min2 = min1;
min1 = j;
} else if (min2 == -1 || huffTree[j].weight < huffTree[min2].weight) {
min2 = j;
}
}
}
huffTree[min1].parent = i;
huffTree[min2].parent = i;
huffTree[i].lchild = min1;
huffTree[i].rchild = min2;
huffTree[i].weight = huffTree[min1].weight + huffTree[min2].weight;
}
}
int main() {
int leafNodes[MAX_LEAF_NODES];
int n, i;
HuffNode huffTree[MAX_LEAF_NODES * 2 - 1];
printf("请输入叶子结点个数n:");
scanf("%d", &n);
printf("请输入%d个叶子结点的权值:", n);
for (i = 0; i < n; i++) {
scanf("%d", &leafNodes[i]);
}
huffman(leafNodes, n, huffTree);
printf("哈夫曼树的结构如下:\n");
printf("结点\t权值\t父结点\t左孩子\t右孩子\n");
for (i = 0; i < 2 * n - 1; i++) {
printf("%d\t%d\t%d\t%d\t%d\n",
i, huffTree[i].weight, huffTree[i].parent,
huffTree[i].lchild, huffTree[i].rchild);
}
return 0;
}
```
输入样例:
```
请输入叶子结点个数n:5
请输入5个叶子结点的权值:6 8 2 3 5
```
输出样例:
```
哈夫曼树的结构如下:
结点 权值 父结点 左孩子 右孩子
0 24 8 3 4
1 11 5 2 0
2 2 6 -1 -1
3 6 8 1 5
4 13 6 -1 -1
5 11 7 3 1
6 15 7 2 4
7 26 -1 5 6
8 50 -1 0 7
```
阅读全文