//霍夫曼算法,构造霍夫曼树
#include <iostream>
using namespace std;
#define MAXSIZE 16
struct HaffNode
{
int weight; //权值
int parent; //双亲下标
int lChild; //左孩子下标
int rChild; //右孩子下标
};
void selectMinWeightIndex(HaffNode* arr, int i, int& minIndex01, int& minIndex02)
{
//找到第一个最小值
for (int j = 1; j <= i - 1; j++)
{
if (arr[j].parent == 0) { minIndex01 = j; }
}
for (int j = 1; j <= i - 1; j++)
{
if (arr[j].parent == 0)
{
if (arr[minIndex01].weight > arr[j].weight) { minIndex01 = j; }
}
}
//找到第二个最小值
for (int j = 1; j <= i - 1; j++)
{
if (arr[j].parent == 0 && j != minIndex01) { minIndex02 = j; }
}
for (int j = 1; j <= i - 1; j++)
{
if (arr[j].parent == 0 && j != minIndex01)
{
if (arr[minIndex02].weight > arr[j].weight) { minIndex02 = j; }
}
}
}
void createHaffmanTree()
{
HaffNode* arr;
arr = new HaffNode[MAXSIZE]; //总共有2n-1个结点,开辟2n大小的空间,0号位置不存储数据
for (int i = 1; i <= MAXSIZE / 2; i++) { cin >> arr[i].weight; arr[i].parent = arr[i].lChild = arr[i].rChild = 0; } //初始化数组
for (int i = MAXSIZE / 2 + 1; i <= MAXSIZE - 1; i++)
{
//找到两个最小值
int minIndex01, minIndex02;
selectMinWeightIndex(arr, i, minIndex01, minIndex02);
arr[i].weight = arr[minIndex01].weight + arr[minIndex02].weight;
arr[i].parent = 0;
arr[i].lChild = minIndex01;
arr[i].rChild = minIndex02;
arr[minIndex01].parent = arr[minIndex02].parent = i;
if (i == MAXSIZE - 1) { arr[i].parent = 0; }
}
for (int i = 1; i <= MAXSIZE - 1; i++)
{
cout << i << ": " << "权值:" << arr[i].weight << "\t";
cout << "双亲下标:" << arr[i].parent << "\t";
cout << "左孩子下标:" << arr[i].lChild << "\t";
cout << " " << left << setw(4) << "右孩子下标:" << arr[i].rChild << endl;
}
}
int main() {
createHaffmanTree();
system("pause");
return 0;
}
霍夫曼算法,构造霍夫曼树 (C++)
于 2022-10-02 17:40:31 首次发布