[Data structure] Huffman coding

Designing Huffman coding is divided into two steps :

1. Build a Huffman tree

Assuming that the message used for communication consists of 8 letters, the frequencies of letters appearing in the message are 0.07, 0.19, 0.02, 0.06, 0.32, 0.03, 0.21, and 0.10.

First of all, for the sake of brevity, we rewrite these frequencies as 7, 19, 2, 6, 32, 3, 21, 10. At this time, we understand the frequency of the message as the weight and arrange it in ascending order to get 2, 3, 6 , 7, 10, 19, 21, 32, construct a binary tree with the two smaller numbers in this set of data, and add the weights of these two numbers to obtain the weight of the formed binary tree, and get a new array 5, 6, 7, 10, 19, 21, 32, repeat this process, as shown in the figure:

2. Design Huffman coding 

Mark the line between any node of the Huffman tree and its left child as 0, and the line between its right child and its right child as 1, and then read the Huffman code according to the path, as shown in the figure:

For example, the Huffman encoding of 2 (the letter with frequency 0.02) is: 00000

       The Huffman code for 32 (the letter with frequency 0.32) is: 01

Guess you like

Origin blog.csdn.net/2301_77112634/article/details/130669172