//构建哈夫曼树\n\tn = 0;\n\tfor (i = 0; i < MAX; i++) {\n\t if (header[i].count == 0)\n\t continue;\n\t n++;\n\t}\n\tm = 2 * n - 1;\n\tfor (i = n; i < m; i++)\n\t{\n\t int min1 = 9999999;//最小权值初值\n\t for (j = 0; j < i; j++) {\n\t if (header[j].parent != -1)\n\t continue;\n\t /parent!=-1说明该结点已存在哈夫曼\n\t 树中,跳出循环重新选择新结点/\n\t if (min1 > header[j].count) {\n\t pt1 = j;\n\t min1 = header[j].count;\n\t }\n\t }\n\t header[i].count = header[pt1].count;\n\t header[pt1].parent = i;\n\t header[i].lch = pt1;\n\n\t min1 = 999999999;\n\t for (j = 0; j < i; j++) {\n\t if (header[j].parent != -1)\n\t continue;\n\t if (min1 > header[j].count) {\n\t pt1 = j;\n\t min1 = header[j].count;\n\t }\n\t }\n\n\t header[i].count += header[pt1].count;\n\t header[i].rch = pt1;\n\t header[pt1].parent = i;\n\t}\n\n\t//求哈夫曼编码\n\tfor (i = 0; i < n; i++) {\n\t f = i;\n\t header[i].bits[0] = 0;//根结点编码0\n\t while (header[f].parent != -1) {\n\t j = f;\n\t f = header[f].parent;\n\t if (header[f].lch == j) {//置左分支编码0\n\t j = strlen(header[i].bits);\n\t memmove(header[i].bits + 1, header[i].bits, j + 1);\n\t header[i].bits[0] = '0';\n\t }\n\t else {//置右分支编码1\n\t j = strlen(header[i].bits);\n\t memmove(header[i].bits + 1, header[i].bits, j + 1);\n\t header[i].bits[0] = '1';\n\t }\n\t }\n\t}

C语言实现哈夫曼树构建与编码算法

原文地址: https://www.cveoy.top/t/topic/pwPd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录