用C语言写出哈夫曼树的代码和注释
时间: 2024-05-14 15:19:16 浏览: 84
C语言版的哈夫曼树.zip
以下是用C语言实现哈夫曼树的代码和注释:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX 100 //定义最大节点数
typedef struct node {
int weight; //权值
int parent; //双亲节点下标
int left; //左孩子节点下标
int right; //右孩子节点下标
} Node, *HuffmanTree;
//初始化哈夫曼树
void InitHuffmanTree(HuffmanTree ht, int n) {
int i;
for (i = 0; i < 2 * n - 1; i++) {
ht[i].weight = ht[i].parent = ht[i].left = ht[i].right = 0;
}
}
//构建哈夫曼树
void CreateHuffmanTree(HuffmanTree ht, int n) {
int i, j, p1, p2, min1, min2;
for (i = 0; i < n; i++) { //初始化叶子节点
printf("请输入第%d个权值: ", i + 1);
scanf("%d", &ht[i].weight);
}
for (i = n; i < 2 * n - 1; i++) { //初始化非叶子节点
ht[i].weight = ht[i].parent = ht[i].left = ht[i].right = 0;
}
for (i = n; i < 2 * n - 1; i++) { //构建哈夫曼树
min1 = min2 = 32767; //初始化最小值为最大整数
p1 = p2 = 0;
for (j = 0; j < i; j++) { //找出权值最小的两个节点
if (ht[j].parent == 0) { //父节点为0表示未被选择过
if (ht[j].weight < min1) {
min2 = min1;
p2 = p1;
min1 = ht[j].weight;
p1 = j;
} else if (ht[j].weight < min2) {
min2 = ht[j].weight;
p2 = j;
}
}
}
ht[p1].parent = i; //将找出的两个节点合并为一个新节点
ht[p2].parent = i;
ht[i].left = p1;
ht[i].right = p2;
ht[i].weight = min1 + min2;
}
}
//输出哈夫曼编码
void PrintHuffmanCode(HuffmanTree ht, int n) {
int i, j, c, p;
char *code = (char*)malloc(n * sizeof(char)); //分配存储编码的空间
code[n - 1] = '\0'; //结束符
for (i = 0; i < n; i++) {
printf("第%d个节点的哈夫曼编码为: ", i + 1);
c = i;
p = ht[i].parent;
while (p != 0) { //从叶子节点开始向上遍历
if (ht[p].left == c) { //左子树为0
code[--n] = '0';
} else { //右子树为1
code[--n] = '1';
}
c = p;
p = ht[p].parent;
}
printf("%s\n", &code[n]); //输出编码
}
free(code); //释放空间
}
int main() {
int n;
printf("请输入节点数: ");
scanf("%d", &n);
HuffmanTree ht = (HuffmanTree)malloc((2 * n - 1) * sizeof(Node)); //分配存储节点的空间
InitHuffmanTree(ht, n); //初始化哈夫曼树
CreateHuffmanTree(ht, n); //构建哈夫曼树
PrintHuffmanCode(ht, n); //输出哈夫曼编码
free(ht); //释放空间
return 0;
}
```
注释已在代码中添加。以上是一个简单的哈夫曼树实现,仅供参考。
阅读全文