Algorithm BASICS (9): super detailed optimal binary tree construction (2) Coding

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.