哈夫曼樹


聲明:圖片及內容基於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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM