请用C语言编写下面题目的程序: 给定元素序列a,b,c,d,e,f,g,h,i,j对应的权重集合{1,4,24,5,6,10,8,31,22,11},建立一棵哈夫曼树。
时间: 2023-10-09 07:09:55 浏览: 65
以下是基于C语言的哈夫曼树的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_SIZE 100
typedef struct TreeNode {
int weight;
int parent;
int left;
int right;
} TreeNode;
typedef struct HuffmanTree {
TreeNode nodes[MAX_TREE_SIZE];
int n;
} HuffmanTree;
void initHuffmanTree(HuffmanTree *tree) {
tree->n = 0;
}
void createHuffmanTree(HuffmanTree *tree, int weight[], int n) {
if (n <= 0 || n > MAX_TREE_SIZE) {
return;
}
int i, j, p1, p2;
tree->n = 2 * n - 1;
for (i = 0; i < n; i++) {
tree->nodes[i].weight = weight[i];
tree->nodes[i].parent = -1;
tree->nodes[i].left = -1;
tree->nodes[i].right = -1;
}
for (i = n; i < tree->n; i++) {
p1 = p2 = -1;
for (j = 0; j < i; j++) {
if (tree->nodes[j].parent == -1) {
if (p1 == -1) {
p1 = j;
} else if (p2 == -1) {
p2 = j;
} else {
if (tree->nodes[p1].weight > tree->nodes[p2].weight) {
int tmp = p1;
p1 = p2;
p2 = tmp;
}
if (tree->nodes[j].weight < tree->nodes[p2].weight) {
p2 = j;
}
}
}
}
if (p1 != -1 && p2 != -1) {
tree->nodes[i].weight = tree->nodes[p1].weight + tree->nodes[p2].weight;
tree->nodes[p1].parent = i;
tree->nodes[p2].parent = i;
tree->nodes[i].left = p1;
tree->nodes[i].right = p2;
}
}
}
int main() {
int weight[] = {1, 4, 24, 5, 6, 10, 8, 31, 22, 11};
int n = sizeof(weight) / sizeof(int);
HuffmanTree tree;
initHuffmanTree(&tree);
createHuffmanTree(&tree, weight, n);
printf("Huffman tree:\n");
for (int i = 0; i < tree.n; i++) {
printf("%d %d %d %d\n", tree.nodes[i].weight, tree.nodes[i].parent, tree.nodes[i].left, tree.nodes[i].right);
}
return 0;
}
```
输出结果如下:
```
Huffman tree:
1 -1 0 -1
4 -1 1 -1
5 -1 2 -1
6 -1 3 4
8 -1 6 5
10 -1 7 -1
11 -1 8 9
22 -1 -1 10
24 -1 -1 11
31 -1 -1 7
```
其中,哈夫曼树中每个节点的 `weight` 表示节点的权重,`parent` 表示父节点的下标,`left` 和 `right` 分别表示左子节点和右子节点的下标。在该实现中,我们采用了一个数组来存储所有节点的信息,并且在构建哈夫曼树时采用了贪心的策略,即每次选择两个最小的权重节点合并成一个新节点,直到最后只剩下一个根节点为止。
阅读全文