哈夫曼树与哈夫曼编码c语言代码实现,不能使用链表构建
时间: 2024-02-02 19:04:54 浏览: 82
以下是使用数组实现哈夫曼树和哈夫曼编码的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // 最大节点数
// 哈夫曼树节点结构体
typedef struct
{
int weight; // 权重
int parent; // 父节点下标
int lchild; // 左子节点下标
int rchild; // 右子节点下标
} HuffmanTreeNode;
// 构建哈夫曼树
void CreateHuffmanTree(HuffmanTreeNode huffmanTree[], int w[], int n)
{
int i, j, m1, m2, x1, x2;
// 初始化哈夫曼树
for (i = 0; i < 2 * n - 1; i++)
{
huffmanTree[i].weight = 0;
huffmanTree[i].parent = -1;
huffmanTree[i].lchild = -1;
huffmanTree[i].rchild = -1;
}
// 初始化叶子节点
for (i = 0; i < n; i++)
{
huffmanTree[i].weight = w[i];
}
// 构建哈夫曼树
for (i = 0; i < n - 1; i++)
{
m1 = m2 = 10000;
x1 = x2 = 0;
// 找到权值最小的两个节点
for (j = 0; j < n + i; j++)
{
if (huffmanTree[j].weight < m1 && huffmanTree[j].parent == -1)
{
m2 = m1;
x2 = x1;
m1 = huffmanTree[j].weight;
x1 = j;
}
else if (huffmanTree[j].weight < m2 && huffmanTree[j].parent == -1)
{
m2 = huffmanTree[j].weight;
x2 = j;
}
}
huffmanTree[x1].parent = n + i;
huffmanTree[x2].parent = n + i;
huffmanTree[n + i].weight = huffmanTree[x1].weight + huffmanTree[x2].weight;
huffmanTree[n + i].lchild = x1;
huffmanTree[n + i].rchild = x2;
}
}
// 哈夫曼编码
void HuffmanEncoding(HuffmanTreeNode huffmanTree[], int n, char** huffmanCode)
{
int i, j, c, p;
char* code;
// 分配空间保存哈夫曼编码
for (i = 0; i < n; i++)
{
code = (char*) malloc(n * sizeof(char));
code[n - 1] = '\0';
huffmanCode[i] = code;
c = i;
p = huffmanTree[c].parent;
while (p != -1)
{
if (huffmanTree[p].lchild == c)
{
code[n - 2] = '0';
}
else
{
code[n - 2] = '1';
}
c = p;
p = huffmanTree[c].parent;
--n;
}
}
}
int main()
{
int w[] = {5, 29, 7, 8, 14, 23, 3, 11}; // 权值
int n = sizeof(w) / sizeof(int); // 节点数
HuffmanTreeNode huffmanTree[MAX_SIZE];
char* huffmanCode[MAX_SIZE];
CreateHuffmanTree(huffmanTree, w, n);
HuffmanEncoding(huffmanTree, n, huffmanCode);
// 输出哈夫曼编码
for (int i = 0; i < n; i++)
{
printf("%d: %s\n", w[i], huffmanCode[i]);
}
return 0;
}
```
在上面的代码中,`CreateHuffmanTree` 函数用于构建哈夫曼树,`HuffmanEncoding` 函数用于计算哈夫曼编码。其中,`huffmanTree` 数组用于保存哈夫曼树节点,`huffmanCode` 数组用于保存哈夫曼编码。`MAX_SIZE` 宏定义了最大节点数,可以根据实际情况进行修改。在运行时,程序会输出每个节点的权值和哈夫曼编码。
阅读全文