哈夫曼樹 C 實現

2021-07-05 19:30:56 字數 1450 閱讀 5675

#include using namespace std; 

#define maxbit 10

#define maxvalue 10000

#define maxleaf 100

#define maxnode maxleaf*2-1

//定義哈夫曼樹編碼型別

typedef structcodetype;

//定義哈夫曼樹結點型別

typedef struct htnode;

void createhfmtree(htnode h[maxnode],int n); //構造哈夫曼樹

void showcode(codetype code[maxnode],htnode h[maxnode],int n); //顯示葉子的字元和其對應的二進位制編碼

void compilecode(char str,int n,codetype code[maxleaf],htnode h[maxnode]);//輸入字串,得到二進位制編碼

void decompilecode(char num,int n,codetype code[maxleaf],htnode h[maxnode]);//輸入二進位制編碼得到字串

void main()

//構造哈夫曼樹

void createhfmtree(htnode h[maxnode],int n)

cout<<"請輸入葉子節點的字元:";

for(i=0;i>h[i].ch;

} cout<<"請輸入葉子節點的權重:";

for(i=0;i>h[i].weight;

} for(i=0;ielse if(h[j].weight}

h[n+i].weight=h[s1].weight+h[s2].weight;//父結點的權重是左孩子和右孩子的權重之和

h[s1].parent=h[s2].parent=n+i;

h[n+i].lchild=s1;h[n+i].rchild=s2; }}

//顯示葉子的字元和其對應的二進位制編碼

void showcode(codetype code[maxnode],htnode h[maxnode],int n)

for(j=cd.start+1;j} for(i=0;i}//輸入字串,得到二進位制編碼

void compilecode(char str,int n,codetype code[maxleaf],htnode h[maxnode])

} cout<<" ";

} cout<}//輸入二進位制編碼得到字串

void decompilecode(char num,int n,codetype code[maxleaf],htnode h[maxnode])

else if(num[i]=='1')

if(j} cout<}

哈夫曼樹與哈夫曼編碼(C 實現)

1 對給定的n個權值構成n棵二叉樹的初始集合f 其中每棵二叉樹ti中只有乙個權值為wi的根結點,它的左右子樹均為空。2 在f中選取兩棵根結點權值最小的樹作為新構造的二叉樹的左右子樹,新二叉樹的根結點的權值為其左右子樹的根結點的權值之和。3 從f中刪除這兩棵樹,並把這棵新的二叉樹同樣以公升序排列加入到...

哈夫曼樹C 實現

哈夫曼樹的介紹 huffman tree,中文名是哈夫曼樹或霍夫曼樹,它是最優二叉樹。定義 給定n個權值作為n個葉子結點,構造一棵二叉樹,若樹的帶權路徑長度達到最小,則這棵樹被稱為哈夫曼樹。這個定義裡面涉及到了幾個陌生的概念,下面就是一顆哈夫曼樹,我們來看 答。01 路徑和路徑長度 定義 在一棵樹中...

哈夫曼樹C 實現

給定一組具有確定權值的葉子結點,可以造出不同的二叉樹,將其中帶權路徑長度最小的二叉樹稱為哈夫曼樹 huffman tree 哈夫曼節點會儲存節點的權重以及,ch是節點對應的編碼字元的下標,這裡需要過載 哈夫曼樹節點類 class hftnode hftnode int data 哈夫曼樹節點類初始化...