由于能力有限,这里给出缩水版本的哈夫曼树,通过给出的权值列表来生成哈夫曼树,并以前序遍历输出
一、代码:
先上代码,后说废话
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int weight;
int parent;
int lchild;
int rchild;
}TreeNode;
typedef struct HFTree {
TreeNode* data;
int length;
}HFTree;
HFTree* initTree(int* weight, int length) {
HFTree* T = (HFTree*)malloc(sizeof(HFTree));
T->data = (TreeNode*)malloc(sizeof(TreeNode) * (2 * length - 1));
T->length = length;
for (int i = 0; i < length; i++) {
T->data[i].weight = weight[i];
T->data[i].parent = 0;
T->data[i].lchild = -1;
T->data[i].rchild = -1;
}
return T;
}
int* selectMin(HFTree* T) {
int min = 10000;
int secondMin = 10000;
int minIndex;
int secondIndex;
for (int i = 0; i < T->length; i++) {
if (T->data[i].parent == 0) {
if (T->data[i].weight < min) {
min = T->data[i].weight;
minIndex = i;
}
}
}
for (int i = 0; i < T->length; i++) {
if (T->data[i].parent == 0 && i != minIndex) {
if (T->data[i].weight < secondMin) {
secondMin = T->data[i].weight;
secondIndex = i;
}
}
}
int* res = (int*)malloc(sizeof(int) * 2);
res[0] = minIndex;
res[1] = secondIndex;
return res;
}
void createHFTree(HFTree* T) {
int* res;
int min;
int secondMin;
int length = T->length * 2 - 1;
for (int i = T->length; i < length; i++) {
res = selectMin(T);
min = res[0];
secondMin = res[1];
T->data[i].weight = T->data[min].weight + T->data[secondMin].weight;
T->data[i].lchild = min;
T->data[i].rchild = secondMin;
T->data[i].parent = 0;
T->data[min].parent = i;
T->data[secondMin].parent = i;
T->length++;
}
}
void preOrder(HFTree* T, int index) {
if (index != -1) {
printf("%d ", T->data[index].weight);
preOrder(T, T->data[index].lchild);
preOrder(T, T->data[index].rchild);
}
}
int main() {
int weight[7] = { 5,1,3,6,11,2,4 };
HFTree* T = initTree(weight, 7);
createHFTree(T);
preOrder(T, T->length - 1);
printf("\n");
return 0;
}
二、运行结果:
输入的权值列表为{ 5,1,3,6,11,2,4 }
32 12 6 6 3 3 1 2 20 9 4 5 11
D:\visual studio\test.c\x64\Debug\test.c.exe (进程 14740)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
三、分析:
如何根据给出的权值结点列表生成哈夫曼树:
1.从结点列表中选出第一小和第二小的节点,并组成一棵树,父亲结点的权值=两结点权值之和。
2.将生成的新树再次放入结点列表中,重复第一步,直到列表中只剩下一个结点。
附上图