哈夫曼树c语言算权值
时间: 2023-07-01 08:22:33 浏览: 103
哈夫曼树(c语言)
5星 · 资源好评率100%
下面是一个简单的C语言代码片段,用于计算哈夫曼树中每个节点的权值:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODE 100
// 定义哈夫曼树节点结构体
typedef struct _huffman_node {
int weight; // 权值
int parent; // 父节点下标
int left; // 左子节点下标
int right; // 右子节点下标
} HuffmanNode;
// 建立哈夫曼树
void create_huffman_tree(HuffmanNode *tree, int n)
{
int i, j, x1, x2, min1, min2;
// 初始化哈夫曼树节点
for (i = 0; i < 2 * n - 1; i++) {
tree[i].weight = 0;
tree[i].parent = -1;
tree[i].left = -1;
tree[i].right = -1;
}
// 输入每个叶子节点的权值
printf("Please enter the weight of each node:\n");
for (i = 0; i < n; i++) {
scanf("%d", &tree[i].weight);
}
// 构建哈夫曼树
for (i = 0; i < n - 1; i++) {
min1 = min2 = 1000000;
x1 = x2 = 0;
for (j = 0; j < n + i; j++) {
if (tree[j].parent == -1) {
if (tree[j].weight < min1) {
min2 = min1;
x2 = x1;
min1 = tree[j].weight;
x1 = j;
} else if (tree[j].weight < min2) {
min2 = tree[j].weight;
x2 = j;
}
}
}
tree[x1].parent = n + i;
tree[x2].parent = n + i;
tree[n + i].weight = min1 + min2;
tree[n + i].left = x1;
tree[n + i].right = x2;
}
}
int main()
{
int n, i;
HuffmanNode tree[MAX_NODE];
printf("Please enter the number of nodes:\n");
scanf("%d", &n);
create_huffman_tree(tree, n);
printf("The weight of each node is:\n");
for (i = 0; i < 2 * n - 1; i++) {
printf("%d ", tree[i].weight);
}
return 0;
}
```
在上述代码中,我们先定义了一个 `HuffmanNode` 结构体,用于表示哈夫曼树中的每个节点。然后,我们通过 `create_huffman_tree` 函数来建立哈夫曼树,并在其中计算每个节点的权值。最后,在 `main` 函数中输出每个节点的权值。
阅读全文