哈夫曼树的构造算法

哈夫曼算法

  1. 根据 n 个给定的权值  构成n棵二叉树的森林 F = \left \{ T_1,T_2,\cdots T_n\right \},其中 T_i 只有一个带权为 w_i 的根节点。(构造森林全是根)
  2.  在 F 中选取两颗根节点的权值最小的树作为左右子树,构造一颗新的二叉树,且设置新的二叉树的根节点的权值为其左右子树上根节点的权值之和。(选用两小造新树)
  3. 在 F 中删除这两棵树,同时将新得到的二叉树加入森林中。(删除两小添新人)
  4. 重复步骤 2 和步骤 3,知道森林中只有一棵树为止,这棵树即为哈夫曼树。(重复2、3剩单根)

C++实现

#include 
using namespace std;

// 结构定义
struct HTNode
{
    int weight;
    int parent, lchd, rchd;
};

// 打印哈夫曼树
void showHuffmanTree(HTNode* HT, int n)
{
    cout << "weight\t" << "parent\t" << "lchd\t" << "rchd" << endl;
    for(int i = 1; i <= n; i++)
    {
        cout << HT[i].weight << "\t" << HT[i].parent << "\t" << HT[i].lchd << "\t" << HT[i].rchd << endl;
    }
}

// 挑选两棵权重最小的二叉树
int* select(HTNode* HT, int x)
{
    int weightValue_1, weightValue_2;
    int* index = new int[2];
    int flag = 1;
    int n = 0;
    for(int i = 1; i < x; i++)
    {
        if(HT[i].parent == 0 && flag == 1)
        {
            weightValue_1 = HT[i].weight;
            index[0] = i;
            flag = 0;
            continue;
        }
        if(HT[i].parent == 0 && flag == 0)
        {
            weightValue_2 = HT[i].weight;
            index[1] = i;
            n = i + 1;
            break;
        }
    }
    if(weightValue_2 < weightValue_1)
    {
        int temp = weightValue_1;
        int temp_1 = index[0];
        weightValue_1 = weightValue_2;
        weightValue_2 = temp;
        index[0] = index[1];
        index[1] = temp_1;
    }
    for(int i = n; i < x; i++)
    {
        if(HT[i].weight < weightValue_1 && HT[i].parent == 0)
        {
            weightValue_2 = weightValue_1;
            weightValue_1 = HT[i].weight;
            index[1] = index[0];
            index[0] = i;
        }
        else if(HT[i].weight < weightValue_2 && HT[i].parent == 0)
        {
            weightValue_2 = HT[i].weight;
            index[1] = i;
        }
    }
    return index;
}

HTNode* creatHuffmanTree(int n)
{
    int m = 2 * n - 1;
    HTNode* HT = new HTNode[m + 1];
    // 初始化
    for(int i = 1; i <= m; i++)
    {
        HT[i].parent = 0;
        HT[i].lchd = 0;
        HT[i].rchd = 0;
    }
    for(int i = 1; i <= n; i++)
    {
        cout << "请输入第 " << i << " 个权重:";
        cin >> HT[i].weight;
    }
    // n - 1 次合并
    for(int i = n + 1; i <= m; i++)
    {
        int* s = select(HT, i);
        HT[s[0]].parent = i;
        HT[s[1]].parent = i;
        HT[i].lchd = s[0];
        HT[i].rchd = s[1];
        HT[i].weight = HT[s[0]].weight + HT[s[1]].weight;
    }
    return HT;
}

void test01()
{
    HTNode* HT = creatHuffmanTree(8);
    showHuffmanTree(HT, 15);
}

int main()
{
    test01();

    system("pause");
    return 0;
}

运行结果

假设  n = 8, w = \left \{ 5,29,7,8,14,23,3,11 \right \}, 哈夫曼树如下:

哈夫曼树的构造算法_第1张图片

 

你可能感兴趣的:(桃子学C++,数据结构与算法基础,算法,huffman,tree,霍夫曼树)