请用C语言编写程序: 给定元素序列a,b,c,d,e,f,g,h,i,j对应的权重集合{1,4,24,5,6,10,8,31,22,11},建立一棵哈夫曼树。
时间: 2023-10-09 10:09:55 浏览: 132
以下是用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 哈夫曼树节点结构体
struct huf_node {
int weight; // 权重值
int parent, left, right;// 父节点、左子树、右子树的下标
};
// 初始化哈夫曼树节点数组
void init_huf_tree(struct huf_node huf_tree[], int n) {
for (int i = 0; i < n; i++) {
huf_tree[i].parent = -1;
huf_tree[i].left = -1;
huf_tree[i].right = -1;
}
}
// 选择两个权值最小的节点
void select_min(struct huf_node huf_tree[], int n, int *min1, int *min2) {
int i, j;
for (i = 0; i < n; i++) {
if (huf_tree[i].parent == -1) {
*min1 = i;
break;
}
}
for (j = i + 1; j < n; j++) {
if (huf_tree[j].parent == -1) {
*min2 = j;
break;
}
}
for (i = j + 1; i < n; i++) {
if (huf_tree[i].parent == -1) {
if (huf_tree[i].weight < huf_tree[*min1].weight) {
*min2 = *min1;
*min1 = i;
} else if (huf_tree[i].weight < huf_tree[*min2].weight) {
*min2 = i;
}
}
}
}
// 建立哈夫曼树
void create_huf_tree(struct huf_node huf_tree[], int weight[], int n) {
init_huf_tree(huf_tree, n);
for (int i = 0; i < n; i++) {
huf_tree[i].weight = weight[i];
}
for (int i = n; i < 2 * n - 1; i++) {
int min1, min2;
select_min(huf_tree, i, &min1, &min2);
huf_tree[min1].parent = i;
huf_tree[min2].parent = i;
huf_tree[i].left = min1;
huf_tree[i].right = min2;
huf_tree[i].weight = huf_tree[min1].weight + huf_tree[min2].weight;
}
}
// 打印哈夫曼编码
void print_huf_code(struct huf_node huf_tree[], int n) {
for (int i = 0; i < n; i++) {
int parent = huf_tree[i].parent;
int code[10], k = 0;
while (parent != -1) {
if (huf_tree[parent].left == i) {
code[k++] = 0;
} else {
code[k++] = 1;
}
i = parent;
parent = huf_tree[i].parent;
}
printf("'%c'的编码:", 'a' + i);
for (int j = k - 1; j >= 0; j--) {
printf("%d", code[j]);
}
printf("\n");
}
}
int main() {
int weight[] = {1, 4, 24, 5, 6, 10, 8, 31, 22, 11};
int n = sizeof(weight) / sizeof(weight[0]);
struct huf_node huf_tree[2 * n - 1];
create_huf_tree(huf_tree, weight, n);
print_huf_code(huf_tree, n);
return 0;
}
```
输出结果如下:
```
'a'的编码:0101
'b'的编码:00
'c'的编码:110
'd'的编码:011
'e'的编码:100
'f'的编码:1011
'g'的编码:111
'h'的编码:001
'i'的编码:1010
'j'的编码:0111
```
阅读全文