哈夫曼树
声明:图片及内容基于https://www.bilibili.com/video/BV1MK411j7CR?from=articleDetail
相关概念
特点
构造过程
存储结构
代码
#include<iostream>
#include<vector>
#include <limits.h>
#include<iomanip>
using namespace std;
struct element {
int weight;
int lchild, rchild, parent;
};
void select(element huffTree[], int n, int& s1, int& s2); //传递引用
void HuffmanTree(element huffTree[], int w[], int n) {
for (int i = 0; i < 2 * n - 1; i++) { //初始化哈夫曼树 注意2*n-1给结点
huffTree[i].lchild = -1;
huffTree[i].parent = -1;
huffTree[i].rchild = -1;
}
for (int i = 0; i < n; i++) {
huffTree[i].weight = w[i]; //复制权值
}
for (int k = n; k < 2 * n - 1; k++) {
int i1, i2; //i1最小,i2次小 为下标
select(huffTree, k, i1, i2); //注意这里必须传k,k是个变量,代表已经有k个结点作为待选数据,且每次k都增加
huffTree[k].weight = huffTree[i1].weight + huffTree[i2].weight;
huffTree[i1].parent = k;
huffTree[i2].parent = k;
huffTree[k].lchild = i1;
huffTree[k].rchild = i2;
cout << "最小下标:" << i1 << " 次小下标:" << i2 << endl;
}
}
void select(element huffTree[], int n, int& s1, int& s2) { //传递引用
int i;
s1 = s2 = 0;
int min1 = INT_MAX;//最小值,INT_MAX在<limits.h>中定义的,INT_MAX是最大值2^31-1
int min2 = INT_MAX;//次小值,找最小值就默认初始值为最大值
for (i = 0; i < n; ++i)
{
if (huffTree[i].parent == -1)
{//筛选没有父节点的最小和次小权值下标
if (huffTree[i].weight < min1)
{//如果比最小值小
min2 = min1; //min1不是最小值了,成为次小值,赋给min2
s2 = s1;
min1 = huffTree[i].weight; //把新的最小值赋给min1
s1 = i;
}
else if ((huffTree[i].weight >= min1) && (huffTree[i].weight < min2))
{//如果大于等于最小值,且小于次小值
min2 = huffTree[i].weight; //更新最小值
s2 = i;
}
else
{//如果大于次小值,则什么都不做
;
}
}
}
}
int main() {
int n; //结点个数
cout << "请输入结点个数:" << endl;
cin >> n;
int w[100];
cout << "请输入" << n << "个权值" << endl;
for (int i = 0; i < n; i++) { //初始化权值
int t;
cin >> t;
w[i] = t;
}
struct element huffTree[100];
HuffmanTree(huffTree, w, n);
cout << "打印哈夫曼树的数组内容:"<<endl;
cout << "weight parent lchild rchild" << endl;
for (int i = 0; i < 2*n-1; i++) {
cout << setw(2) << huffTree[i].weight << " " << setw(2) << huffTree[i].parent
<< " " << setw(2) << huffTree[i].lchild << " " << setw(2) << huffTree[i].rchild << endl;
}
return 0;
}
输入:
4
2 4 5 3
输出:
最小下标:0 次小下标:3
最小下标:1 次小下标:2
最小下标:4 次小下标:5
打印哈夫曼树的数组内容:
weight parent lchild rchild
2 4 -1 -1
4 5 -1 -1
5 5 -1 -1
3 4 -1 -1
5 6 0 3
9 6 1 2
14 -1 4 5