霍夫曼算法,构造霍夫曼树 (C++)

//霍夫曼算法,构造霍夫曼树
#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;
}

结果:

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值