1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include <stdlib.h> #include <string.h> #include <stdio.h>
typedef struct { int weight, parent, lchild, rchild; } HfNode, *HuffmanTree; typedef char **HuffmanCode;
void CreatHfTree(HuffmanTree &HT, HuffmanCode &HC, int *w, int n) { void Select(HuffmanTree & HT, int s, int &s1, int &s2); int m = 2 * n - 1; HT = (HuffmanTree)malloc((m + 1) * sizeof(HfNode)); HuffmanTree p = HT + 1; for (int i = 1; i <= n; ++i, ++p) { *p = {w[i - 1], 0, 0, 0}; } for (int i = n + 1; i <= m; ++i, ++p) { *p = {0, 0, 0, 0}; } for (int i = n + 1; i <= m; ++i) { int s1, s2; Select(HT, i - 1, s1, s2); HT[i].weight = HT[s1].weight + HT[s2].weight; HT[s1].parent = i; HT[s2].parent = i; HT[i].lchild = s1; HT[i].rchild = s2; } HC = (HuffmanCode)malloc((n + 1) * sizeof(HuffmanCode)); char *cd = (char *)malloc(n * sizeof(char)); cd[n - 1] = '\0'; for (int t = 1; t <= n; ++t) { int start = n - 1; for (int c = t, f = HT[c].parent; f != 0; c = f, f = HT[f].parent) { if (c == HT[f].lchild) { cd[--start] = '0'; } else { cd[--start] = '1'; } } HC[t] = (char *)malloc((n - start) * sizeof(char)); strcpy(HC[t], &cd[start]); } free(cd); printf("打印哈夫曼树的存储结构如下;\n"); for (int x = 1; x <= m; ++x) { printf("第%d个结点 权值为:%d 左孩子为:%d 右孩子为:%d \n", x, HT[x].weight, HT[x].lchild, HT[x].rchild); } printf("打印哈夫曼编码如下:\n"); for (int j = 1; j <= n; ++j) { printf("第%d个结点权值为%d的哈夫曼编码为%s\n", j, HT[j].weight, HC[j]); } }
void Select(HuffmanTree &HT, int s, int &s1, int &s2) { s1 = 0; s2 = 0; for (int i = 1; i <= s; ++i) { if (HT[i].parent == 0) { if (s1 == 0 || HT[i].weight < HT[s1].weight) { s2 = s1; s1 = i; } else if (s2 == 0 || HT[i].weight < HT[s2].weight) { s2 = i; } } } } int main() { int n = 8; int w[8] = {3, 4, 7, 2, 9, 8, 16, 10}; HuffmanTree HT; HuffmanCode HC; printf("已知有%d个结点且已知权值,以此创建哈夫曼树如下:", n); printf("HT为一棵哈夫曼树,HC用于存储哈夫曼编码:"); CreatHfTree(HT, HC, &w[0], n); system("pause"); return 0; }
|