#include <iostream> #include <cstdio> #define INF 1<<30using namespace std;//Huffman tree Implementation// Huffman Tree Features: If there are n leaf nodes, then the sum of points is 2*n-1. The more frequently the code accesses the shorter the struct node{int parent, Lson, Rson;int Val; Number of visits};void createtree (node p[], int n, int total)//total=2*n-1{for (int t=0; t<total; ++t)//Initialize {p[t].parent = P[t ].lson = P[t].rson =-1;} for (int i=n; i<total; ++i) {int min1, min2, L, R; The maximum and the second largest value min1 = min2 = Inf;l = r = -1;for (int t=0; t<i; ++t)//traversal looks for two smallest points, which is the {if (p[t].parent =-1 Al<min1) {r = l;l = t;min2 = Min1;min1 = P[t].val;} else if (p[t].val<min2) {r = t;min2 = P[t].val;}}} P[i].val = min1 + min2;p[l].parent = p[r].parent = I;p[i].lson = L;p[i].rson = r;}} struct Code{int K;char c[100];}; void Huffmancode (node p[], int n, code c1[]) {for (int t=0; t<n; ++t) {int pre = P[t].parent;int g = t;c1[t].k = 0;while (P Re! =-1) {if (P[pre].lson = = g) {c1[t].c[c1[t].k++] = ' 0 ';} else {c1[t].c[c1[t].k++] = ' 1 ';} G = Pre;pre = P[pre].parent;} c1[t].k--;}} int main () {nOde p[4*2-1];for (int t=0; t<4; ++t) {p[t].val = 2*t+1;} Createtree (P, 4, 2*4-1); Code C[4];huffmancode (P, 4, c); for (int t=0; t<4; ++t) {int k = c[t].k;printf ("%d:", p[t].val); fo R (int j=k; j>=0;--j) {printf ("%c", C[t].c[j]);} printf ("\ n");} return 0;}
Operation Result:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Huffman Tree Realization