Huffman樹及編碼C 實現

2021-07-11 22:20:45 字數 1625 閱讀 5008

by qianghaohao(johar)   

huffman樹採用陣列實現,編碼時從葉子節點開始向上編碼,所以採用deque支援前插的

容器來存放每個葉子的編碼。

**如下:

#include #include #include #include #include using namespace std;

typedef struct haffmantree;

// h:haffman樹 w:權向量

void createhaffmantree(vector&h, const vectorw) else

h[i].parent = -1;

h[i].lchild = -1;

h[i].rchild = -1;

h[i].flag = false;

}condi = n -1;

int mini1, mini2; // mini1:最小值 mini2:次小值

int x1, x2; //記錄最小值和次小值位置

for (int i = 0; i < condi; i++) else if (h[j].weight < mini2 && !h[j].flag)

}h[n + i].weight = mini1 + mini2;

h[n + i].lchild = x1;

h[n + i].rchild = x2;

h[x1].parent = n + i;

h[x2].parent = n + i;

h[x1].flag = true;

h[x2].flag = true;

}}// h:haffman樹 n:葉子個數 c:葉子編碼

void haffmanencode(vector&h, int n, vector> &c) else

_child = _parent; //繼續往上編碼

_parent = h[_parent].parent;}}

}vectorweight = ; //權向量

vectorhaff(2 * weight.size() - 1); //haffman樹向量

vector> encode(weight.size()); // haffman編碼向量

int main ()

;\n";

cout << "*******哈夫曼樹********" << endl;

cout << "節點 左孩子 右孩子" << endl;

for (vector::iterator it = haff.begin(); it != haff.end(); it++) else

if (it->rchild >= 0) else

cout << "\n";

} //哈夫曼編碼

int n = weight.size();

haffmanencode(haff, n, encode);

cout << "\n******哈夫曼編碼:*******" << endl;

for (int i = 0; i < n; i++)

return 0;

}

Huffman編碼樹的C 實現

用c 實現huffman編碼樹,如下 標頭檔案 pragma once include include include include includeusing namespace std class huffman cpp檔案 include huffman.h huffman huffman v...

Huffman編碼C 實現

huffman.h 葉子結點為n的哈夫曼樹共有2n 1個結點 ifndef huffman h define huffman h class huffmannode huffmannode const char data,const double wt,const int pa 1,const in...

Huffman編碼C實現

huffman編碼 根據huffman樹進行編碼的,用到的資料結構是二叉樹。typedef int elemtype typedef struct binarytree 2 構建最優二叉樹 void createhuffman int leafnum,binarytree huffmantree e...