Huffman編碼樹的C 實現

2021-08-20 05:48:28 字數 1171 閱讀 2042

用c++實現huffman編碼樹,**如下

標頭檔案:

#pragma once

#include#include #include#include#includeusing namespace std;

class huffman

;

cpp檔案

#include "huffman.h"

huffman::huffman()

void huffman::leafhuffman(int setweight, string str)

void huffman::nodehuffman(int setweight, huffman * setleft, huffman * setright)

huffman::~huffman()

bool huffman::isleaf()

bool huffman::myhuffumancomepare(huffman * node1, huffman * node2)

void huffman::getnode(huffman * root, string & prefix, map& result)

else

getnode(root->left, prefix, result);

//還原原來的路徑,回溯

prefix = m_prefix;

//處理右子樹

prefix += "1";

//如果是葉子結點,則輸出, 否則遞迴列印右子樹

if (root->right->right == null)

else

getnode(root->right, prefix, result);

}int huffman::buildhuffuman()

sort(weightarray.begin(), weightarray.end(), myhuffumancomepare);

while ((int)weightarray.size() > 1)

//輸出編碼

string str;

mapresult;

getnode(weightarray[0], str, result);

} return 0;

}

Huffman樹及編碼C 實現

by qianghaohao johar huffman樹採用陣列實現,編碼時從葉子節點開始向上編碼,所以採用deque支援前插的 容器來存放每個葉子的編碼。如下 include include include include include using namespace std typedef ...

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...