给定n个叶子结点和权值,建立哈夫曼树并输出,编写代码
时间: 2024-03-09 14:49:14 浏览: 91
好的,以下是建立哈夫曼树并输出的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 哈夫曼树结构体
typedef struct HuffmanTree {
int weight;
struct HuffmanTree *left;
struct HuffmanTree *right;
} HuffmanTree;
// 建立哈夫曼树
HuffmanTree *createHuffmanTree(int *weight, int n) {
// 申请空间,初始化叶子节点
HuffmanTree **nodes = (HuffmanTree **) malloc(sizeof(HuffmanTree *) * n);
for (int i = 0; i < n; i++) {
HuffmanTree *node = (HuffmanTree *) malloc(sizeof(HuffmanTree));
node->weight = weight[i];
node->left = NULL;
node->right = NULL;
nodes[i] = node;
}
// 构建哈夫曼树
while (n > 1) {
// 找到最小的两个节点
int min1 = 0, min2 = 1;
if (nodes[min1]->weight > nodes[min2]->weight) {
int temp = min1;
min1 = min2;
min2 = temp;
}
for (int i = 2; i < n; i++) {
if (nodes[i]->weight < nodes[min1]->weight) {
min2 = min1;
min1 = i;
} else if (nodes[i]->weight < nodes[min2]->weight) {
min2 = i;
}
}
// 合并最小的两个节点
HuffmanTree *parent = (HuffmanTree *) malloc(sizeof(HuffmanTree));
parent->weight = nodes[min1]->weight + nodes[min2]->weight;
parent->left = nodes[min1];
parent->right = nodes[min2];
// 删除原来的两个节点并将新节点加入数组
if (min1 < min2) {
for (int i = min2; i < n - 1; i++) {
nodes[i] = nodes[i + 1];
}
}
for (int i = min1; i < n - 1; i++) {
nodes[i] = nodes[i + 1];
}
nodes[n - 2] = parent;
n--;
}
// 返回根节点
return nodes[0];
}
// 输出哈夫曼树
void printHuffmanTree(HuffmanTree *root) {
if (root == NULL) {
return;
}
printf("%d\n", root->weight);
printHuffmanTree(root->left);
printHuffmanTree(root->right);
}
int main() {
int n;
printf("请输入叶子节点个数:");
scanf("%d", &n);
int *weight = (int *) malloc(sizeof(int) * n);
printf("请输入每个叶子节点的权值:");
for (int i = 0; i < n; i++) {
scanf("%d", &weight[i]);
}
HuffmanTree *root = createHuffmanTree(weight, n);
printf("哈夫曼树构建完成,节点权值如下:\n");
printHuffmanTree(root);
return 0;
}
```
运行程序后,按照提示输入叶子节点个数和每个叶子节点的权值,即可创建一个哈夫曼树。然后,程序会输出每个节点的权值,即构成的哈夫曼树。
阅读全文