对于给定的w={2,3,4,7,8,9}权值,试构造一棵哈夫曼树,并给出各个节点的huffman编码及huffman数组的值,写出它的c语言代码
时间: 2023-06-16 10:07:12 浏览: 750
对给定权值的赫夫曼树进行编码
构造哈夫曼树的步骤如下:
1. 将w中的元素按权值从小到大排序。
2. 取出最小的两个权值,构造一个新节点,权值为这两个节点权值之和,将这个新节点放回w中。
3. 重复步骤2,直到w中只剩下一个节点,构成哈夫曼树。
4. 对于每个节点,如果它是左子节点,则它的编码为父节点编码后加一个0,如果它是右子节点,则它的编码为父节点编码后加一个1。
5. 输出每个节点的huffman编码及huffman数组的值。
下面是这个算法的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int weight;
int parent;
int lchild;
int rchild;
}HuffmanNode, *HuffmanTree;
// 建立哈夫曼树
void createHuffmanTree(HuffmanTree tree, int size, int* weight) {
int i, j, k;
int min1, min2;
// 初始化哈夫曼树
for (i = 0; i < 2*size-1; i++) {
tree[i].weight = 0;
tree[i].parent = -1;
tree[i].lchild = -1;
tree[i].rchild = -1;
}
// 将w中的元素按权值从小到大排序
for (i = 0; i < size; i++) {
tree[i].weight = weight[i];
}
for (i = 0; i < size - 1; i++) {
min1 = min2 = MAX_SIZE;
k = -1;
// 取出最小的两个权值
for (j = 0; j < size + i; j++) {
if (tree[j].weight < min1 && tree[j].parent == -1) {
min2 = min1;
min1 = tree[j].weight;
k = j;
} else if (tree[j].weight < min2 && tree[j].parent == -1) {
min2 = tree[j].weight;
}
}
// 构造一个新节点,权值为这两个节点权值之和
tree[k].parent = size + i;
tree[size+i].weight = min1 + min2;
tree[size+i].lchild = k;
// 将这个新节点放回w中
k = -1;
for (j = 0; j < size + i; j++) {
if (tree[j].parent == -1 && tree[j].weight < min2) {
k = j;
break;
}
}
tree[k].parent = size + i;
tree[size+i].rchild = k;
}
}
// 输出哈夫曼编码及huffman数组的值
void huffmanCode(HuffmanTree tree, int size) {
int i, j, k, parent;
int code[size];
for (i = 0; i < size; i++) {
printf("%d的huffman编码为:", tree[i].weight);
j = i;
parent = tree[j].parent;
k = 0;
// 对于每个节点,如果它是左子节点,
// 则它的编码为父节点编码后加一个0,
// 如果它是右子节点,则它的编码为父节点编码后加一个1
while (parent != -1) {
if (tree[parent].lchild == j) {
code[k++] = 0;
} else {
code[k++] = 1;
}
j = parent;
parent = tree[j].parent;
}
for (j = k - 1; j >= 0; j--) {
printf("%d", code[j]);
}
printf("\n");
}
printf("huffman数组的值为:\n");
for (i = 0; i < size; i++) {
printf("%d ", tree[i].weight);
}
printf("\n");
}
int main() {
int weight[] = {2, 3, 4, 7, 8, 9};
int size = sizeof(weight) / sizeof(int);
HuffmanTree tree = (HuffmanTree)malloc(sizeof(HuffmanNode) * (2*size-1));
createHuffmanTree(tree, size, weight);
huffmanCode(tree, size);
return 0;
}
```
阅读全文