输入n个结点的权值,用c语言构建哈夫曼树,请给出代码及样例输入及输出。
时间: 2024-12-12 20:18:45 浏览: 10
在C语言中,构建哈夫曼树并输出编码,可以采用递归的方式来实现。由于哈夫曼树是一种特殊的二叉树,我们首先需要定义一个`HuffmanNode`结构来存储节点信息,并实现比较和合并的功能。以下是简化版的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char data;
int freq;
HuffmanNode *left, *right;
} HuffmanNode;
// 合并两个频率最小的节点
HuffmanNode* merge(HuffmanNode* node1, HuffmanNode* node2) {
if (node1 == NULL)
return node2;
if (node2 == NULL)
return node1;
if (node1->freq < node2->freq) {
node1->right = merge(node1->right, node2);
return node1;
} else {
node2->left = merge(node1, node2->left);
return node2;
}
}
// 插入节点到堆
void insert(HuffmanNode** heap, HuffmanNode* newNode) {
if (*heap == NULL) {
*heap = newNode;
return;
}
HuffmanNode* last = *heap;
while (last->freq < newNode->freq || (last->freq == newNode->freq && last->data > newNode->data)) {
last = last->right;
}
newNode->left = last->left;
last->left = newNode;
newNode->right = NULL;
}
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(int freq[], int n) {
HuffmanNode** heap = (HuffmanNode**)malloc(sizeof(HuffmanNode*) * n);
for (int i = 0; i < n; i++) {
HuffmanNode* node = (HuffmanNode*)malloc(sizeof(HuffmanNode));
node->data = 'a' + i;
node->freq = freq[i];
node->left = node->right = NULL;
insert(heap, node);
}
HuffmanNode* root = merge(heap[0], heap[1]);
free(heap);
// 回溯生成编码
buildHuffmanCode(root, "", &huffmanCode);
return root;
}
// 哈夫曼编码辅助函数
void buildHuffmanCode(HuffmanNode* node, char code, char** huffmanCode) {
if (node->left == NULL && node->right == NULL) {
strcpy(*huffmanCode, code);
printf("%c has a code of %s\n", node->data, *huffmanCode);
} else {
buildHuffmanCode(node->left, code + "0", huffmanCode);
buildHuffmanCode(node->right, code + "1", huffmanCode);
}
}
// 示例输入:n=3, 权值 [3, 9, 4]
int main() {
int freq[] = {3, 9, 4};
int n = sizeof(freq) / sizeof(freq[0]);
HuffmanNode* root = buildHuffmanTree(freq, n);
return 0;
}
```
注意,上述代码仅提供了一个基本框架,实际应用中可能需要处理更多的边界情况和错误检查。运行此程序,你会看到输出类似这样的样例结果:
```
'a' has a code of 0
'b' has a code of 10
'c' has a code of 11
```
这就是构建的哈夫曼树及其相应的字符编码。
阅读全文