C/C++語言之哈夫曼樹
阿新 • • 發佈:2018-12-22
原始碼:
//哈夫曼樹演算法 #include <stdio.h> #include <stdlib.h> #define MAX_VALUE 20 typedef struct // 一個結點 { int Weight; bool flag; int Parent, LChild, RChild; } HuffNode, *pHuffNode; //--------------------------------------- typedef struct // Huffman 樹 { int n; // 權個數 int root; // 樹根在陣列中的位置 HuffNode *Huf; // 陣列首地址(動態分配) } HuffTree, *pHuffTree; int main() { HuffTree Tree; int arr[4] = { 1, 5, 4, 8 }; int n = 4; if (n < 1) { return NULL; } else { Tree.n = n; // Tree.root = -1 ; Tree.root = -1; Tree.Huf = (pHuffNode)malloc((2 * n - 1)* sizeof(HuffNode)); for (int i = 0; i < 2 * n - 1;) { Tree.Huf[i].flag = false; // i 結點未加入樹中 Tree.Huf[i].Weight = (i < n) ? arr[i] : 0; Tree.Huf[i].Parent = -1; Tree.Huf[i].LChild = -1; Tree.Huf[i].RChild = -1; i++; } } int i, j, m1, m2, x1, x2; for (i = n; i < 2 * n - 1; i++) // 構造 n-1 個分支結點(非葉子) { m1 = m2 = MAX_VALUE; x1 = x2 = -1; // m1<=m2 for (j = 0; j < i; j++) // 2n-1個結點 { if (Tree.Huf[j].flag != false) { continue; } // j 結點未加入樹中 if (Tree.Huf[j].Weight < m1) { m2 = m1; x2 = x1; m1 = Tree.Huf[j].Weight; x1 = j; } else if (Tree.Huf[j].Weight < m2) { m2 = Tree.Huf[j].Weight; x2 = j; } } Tree.Huf[x1].Parent = i; Tree.Huf[x2].Parent = i; Tree.Huf[x1].flag = true; Tree.Huf[x2].flag = true; Tree.Huf[i].Weight = Tree.Huf[x1].Weight + Tree.Huf[x2].Weight; Tree.Huf[i].LChild = x1; Tree.Huf[i].RChild = x2; } for (int i = 0; i < 2*n - 1;i++) { printf("%d ", Tree.Huf[i].Weight); } free(Tree.Huf); system("pause"); return 0; }