编写程序,输入结点个数及各结点对应的权值,创建哈夫曼树,生成哈夫曼编码并输出。使用C++实现,并给出完整代码
时间: 2024-05-01 19:20:33 浏览: 103
根据结点值和权重建立哈夫曼树哈夫曼代码
4星 · 用户满意度95%
以下是使用C语言实现哈夫曼编码的完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODE_NUM 100
typedef struct Node {
int weight;
int parent;
int lchild;
int rchild;
} Node;
typedef struct Code {
int bit[MAX_NODE_NUM];
int start;
} Code;
void createHuffmanTree(Node *huffmanTree, int nodeNum);
void getHuffmanCode(Node *huffmanTree, Code *huffmanCode, int nodeNum);
int main() {
Node huffmanTree[MAX_NODE_NUM];
Code huffmanCode[MAX_NODE_NUM];
int nodeNum, i;
printf("请输入结点个数:");
scanf("%d", &nodeNum);
printf("请输入各结点的权值:");
for (i = 0; i < nodeNum; ++i) {
scanf("%d", &huffmanTree[i].weight);
huffmanTree[i].parent = -1;
huffmanTree[i].lchild = -1;
huffmanTree[i].rchild = -1;
}
createHuffmanTree(huffmanTree, nodeNum);
getHuffmanCode(huffmanTree, huffmanCode, nodeNum);
printf("哈夫曼编码为:\n");
for (i = 0; i < nodeNum; ++i) {
printf("%d: ", huffmanTree[i].weight);
int j;
for (j = huffmanCode[i].start-1; j >= 0; --j) {
printf("%d", huffmanCode[i].bit[j]);
}
printf("\n");
}
return 0;
}
void createHuffmanTree(Node *huffmanTree, int nodeNum) {
int i, j, min1, min2;
for (i = nodeNum; i < 2*nodeNum-1; ++i) {
huffmanTree[i].weight = 0;
huffmanTree[i].parent = -1;
huffmanTree[i].lchild = -1;
huffmanTree[i].rchild = -1;
}
for (i = nodeNum; i < 2*nodeNum-1; ++i) {
min1 = min2 = -1;
for (j = 0; j < i; ++j) {
if (huffmanTree[j].parent == -1) {
if (min1 == -1 || huffmanTree[j].weight < huffmanTree[min1].weight) {
min2 = min1;
min1 = j;
} else if (min2 == -1 || huffmanTree[j].weight < huffmanTree[min2].weight) {
min2 = j;
}
}
}
huffmanTree[min1].parent = i;
huffmanTree[min2].parent = i;
huffmanTree[i].lchild = min1;
huffmanTree[i].rchild = min2;
huffmanTree[i].weight = huffmanTree[min1].weight + huffmanTree[min2].weight;
}
}
void getHuffmanCode(Node *huffmanTree, Code *huffmanCode, int nodeNum) {
int i, j, parent, current;
for (i = 0; i < nodeNum; ++i) {
huffmanCode[i].start = nodeNum;
current = i;
parent = huffmanTree[current].parent;
while (parent != -1) {
if (huffmanTree[parent].lchild == current) {
huffmanCode[i].bit[--huffmanCode[i].start] = 0;
} else {
huffmanCode[i].bit[--huffmanCode[i].start] = 1;
}
current = parent;
parent = huffmanTree[current].parent;
}
}
}
```
代码中使用了两个结构体,分别用于表示哈夫曼树的结点和哈夫曼编码。在 `createHuffmanTree` 函数中,首先为哈夫曼树的叶子结点赋初值,然后依次选取权值最小的两个结点合并,构建哈夫曼树。在 `getHuffmanCode` 函数中,根据哈夫曼树和每个结点的父节点,生成哈夫曼编码并存储到对应的 `Code` 结构体中。
最后,程序会输出每个权值对应的哈夫曼编码。
阅读全文