c语言实现构建huffman树算法
时间: 2023-07-26 21:08:45 浏览: 101
下面是用C语言实现构建Huffman树算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
// 定义Huffman树节点结构体
typedef struct {
int weight; // 权值
int parent; // 父节点下标
int left; // 左子节点下标
int right; // 右子节点下标
} HuffNode, *HuffTree;
// 定义Huffman编码结构体
typedef struct {
char ch; // 字符
char code[MAX_SIZE]; // 编码
} HuffCode, *HuffCodeTable;
// 选择权值最小的两个节点
void select(HuffTree tree, int n, int *s1, int *s2) {
int i;
int min1, min2;
min1 = min2 = MAX_SIZE;
// 找出第一个权值最小的节点
for (i = 0; i < n; i++) {
if (tree[i].weight < min1 && tree[i].parent == -1) {
min1 = tree[i].weight;
*s1 = i;
}
}
// 找出第二个权值最小的节点
for (i = 0; i < n; i++) {
if (tree[i].weight < min2 && tree[i].parent == -1 && i != *s1) {
min2 = tree[i].weight;
*s2 = i;
}
}
}
// 构建Huffman树
void buildHuffTree(HuffTree tree, int n) {
if (n <= 1) return;
int i, s1, s2;
for (i = 0; i < 2 * n - 1; i++) {
tree[i].parent = -1;
tree[i].left = -1;
tree[i].right = -1;
}
// 构建n-1个节点的Huffman树
for (i = n; i < 2 * n - 1; i++) {
select(tree, i, &s1, &s2);
tree[s1].parent = i;
tree[s2].parent = i;
tree[i].left = s1;
tree[i].right = s2;
tree[i].weight = tree[s1].weight + tree[s2].weight;
}
}
// 获取Huffman编码
void getHuffCode(HuffTree tree, HuffCodeTable table, int n) {
int i, j;
char *code = (char *)malloc(n * sizeof(char));
code[n - 1] = '\0';
for (i = 0; i < n; i++) {
int start = n - 1;
int c = i;
int p = tree[c].parent;
while (p != -1) {
if (tree[p].left == c) {
code[--start] = '0';
} else {
code[--start] = '1';
}
c = p;
p = tree[c].parent;
}
strcpy(table[i].code, &code[start]);
}
free(code);
}
int main() {
int n;
printf("输入字符个数:");
scanf("%d", &n);
// 输入字符及其权值
HuffTree tree = (HuffTree)malloc(sizeof(HuffNode) * (2 * n - 1));
HuffCodeTable table = (HuffCodeTable)malloc(sizeof(HuffCode) * n);
int i;
for (i = 0; i < n; i++) {
printf("输入第%d个字符及其权值:", i + 1);
scanf("%s %d", &table[i].ch, &tree[i].weight);
}
// 构建Huffman树
buildHuffTree(tree, n);
// 获取Huffman编码
getHuffCode(tree, table, n);
// 输出Huffman编码
printf("Huffman编码如下:\n");
for (i = 0; i < n; i++) {
printf("%c: %s\n", table[i].ch, table[i].code);
}
free(tree);
free(table);
return 0;
}
```
这段代码实现了从用户输入字符及其权值,构建Huffman树,获取Huffman编码,输出Huffman编码的功能。在构建Huffman树时,采用的是贪心策略,每次选择权值最小的两个节点进行合并。在获取Huffman编码时,采用的是自底向上的遍历方式,从叶子节点到根节点依次获取每个字符的编码。
阅读全文