C语言 在右侧编辑器中补充代码,编写能对给定n个叶子结点,构建哈夫曼树,给出每个叶子结点对应编码的程序。
时间: 2024-10-27 08:04:00 浏览: 23
在C语言中,我们可以利用递归和队列数据结构来构建哈夫曼树并计算叶子节点的编码。首先,我们需要创建一个结构体`Node`来表示二叉树节点,以及两个辅助函数`addWeight`添加权重到队列和`buildHuffmanTree`来进行哈夫曼树的生成。
```c
#include <stdio.h>
#include <stdlib.h>
#include <queue>
typedef struct Node {
char data;
int weight;
struct Node* left;
struct Node* right;
} Node;
// 添加权重到优先级队列 (最小堆)
void addWeight(Node** heap, int data, int weight) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->weight = weight;
newNode->left = NULL;
newNode->right = NULL;
if (*heap == NULL) {
*heap = newNode;
} else {
Node* temp = *heap;
while (temp && temp->weight < newNode->weight) {
Node* parent = temp;
temp = temp->weight < newNode->weight ? temp->right : temp->left;
}
if (temp->weight > newNode->weight) {
parent->right = newNode;
} else {
parent->left = newNode;
}
}
}
// 构建哈夫曼树并返回根节点
Node* buildHuffmanTree(int n, int* weights, Node** heap) {
// 如果只有一个元素,直接返回它作为叶子节点
if (n == 1) return *heap;
// 异或操作选择最小值合并成新的节点
Node* left = buildHuffmanTree(n - 1, weights, heap);
Node* right = buildHuffmanTree(n - 1, weights + n / 2, heap + n / 2);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = '\0'; // 新节点代表合并后的路径,可以任意赋值
newNode->weight = left->weight + right->weight;
newNode->left = left;
newNode->right = right;
// 将新节点加入到堆中
addWeight(heap, newNode->data, newNode->weight);
return *heap;
}
// 计算并打印叶子节点编码
void printCodes(Node* root, char* codes, int index) {
if (root->left == NULL && root->right == NULL) { // 叶子节点
printf("叶节点 %d 的编码为: %s\n", index, codes);
codes[index] = '\0'; // 结束当前编码字符串
} else {
printCodes(root->left, codes, 2 * index + 1);
printCodes(root->right, codes, 2 * index + 2);
}
}
int main() {
int n;
printf("请输入叶子节点的数量: ");
scanf("%d", &n);
int weights[n];
for (int i = 0; i < n; i++) {
printf("输入第%d个叶子节点的权重: ", i + 1);
scanf("%d", &weights[i]);
}
// 初始化空堆
Node** heap = (Node**)malloc(sizeof(Node*) * n);
for (int i = 0; i < n; i++) {
addWeight(&heap, 'A' + i, weights[i]); // 假设字符'A'至'D'对应4个初始节点
}
Node* huffmanRoot = buildHuffmanTree(n, weights, heap);
// 初始化编码数组
char* codes = (char*)malloc(n * sizeof(char));
memset(codes, 0, n);
printCodes(huffmanRoot, codes, 0);
free(heap);
free(codes);
return 0;
}
```
在这个程序中,我们首先读取每个叶子节点的权重,然后使用哈夫曼编码算法生成一棵哈夫曼树。最后,通过递归遍历树来计算每个叶子节点的编码,并将结果存储在`codes`数组中。
阅读全文