Find the Heman encoding of each character from the leaf to the back end:
Void GetHuffmanCode (HuffmanTree & HT, HuffmanCode & HC, int n) {char * cd; int c; int f; int start; int I = 0; // from the leaf to the root, reverse calculate the Harman encoding printf for each character ("\ n to enter the encoding function... "); HC = (HuffmanCode) malloc (n + 1) * sizeof (char *); // assign n character-encoded header pointer vector cd = (char *) malloc (n * sizeof (char); // allocate the encoded workspace n because there are n leaf nodes cd [n-1] = '\ 0 '; // encode the terminator for (I = 1; I <= n; ++ I) // calculate the hafman encoding {start = n-1 one by one; // encoding Terminator position for (c = I, f = HT [I]. parent; f! = 0; c = f, f = HT [f]. parent) // f! = 0 always go up and go to the root node {if (HT [f]. lchild = c) // determines whether the left child cd [-- start] = '0'; else cd [-- start] = '1 '; // right child} // exit the loop. Find the huffmancode of the leaf node I, open up the space, and assign a value, because HC is char ** type HC [I] = (char *) malloc (n-start) * sizeof (char); strcpy (HC [I], cd + start); printf ("\ n no.: % d. The hafman code for the weight: % d is:", I, HT [I]. weight); puts (HC [I]);} free (cd); // release the Workspace
This code can be added to the header file of the previous article or in main. cpp. main. cpp is as follows:
# Include "stdafx. h "// # include" BasicGraph2.h "# include" HuffmanCode. h "void main () {HuffmanTree HT; HuffmanCode code; int n = 8; int m = 15; int arr [] = }; if (HuffmanCoding (HT, arr, n) // construct the haffmantree ShowHT (HT, n); // test whether the GetHuffmanCode (HT, code, n) is correct ); // obtain the Haffman encoding and save the result in the code}
Running result:
Structure:
Note: The numbers 8 and 11 are the opposite of what I originally painted.