Topic: Use Huffman coding method to realize the coding and decoding of communication characters
Effect picture:
Enter the original string code to implement HuffmanTree
Enter weights to implement HuffmanTree
You can enter numbers, characters, spaces, and symbols at the same time
Ideas:
①: First, in order to construct HuffmanTree, we need to process the input character weights. Here, since the main input method is input string, the corresponding function is used to calculate the weight of each character or directly input There are two ways for the weight of each character, and the corresponding processing methods are slightly different, but they are generally the same. I defined a double type weight array to store the weight of the character, and then defined a code array to store Each non-repeated character can solve the problem that when the user enters a string, even if there are a large number of repeated characters, the correct weight can be calculated. After the complete weight is obtained, we can start to build HuffmanTree.
②First, we establish the corresponding number of HuffmanTree nodes according to the size of the code array, and at the same time initialize these nodes, and then we establish a priority queue q of the HuffmanTree node type, and proceed from small to large according to the weight of the node Internal sorting, so as to prepare for our next formal construction of HuffmanTree. Every time we take out the first two elements in q and merge them, we realize that each merged node is the node with the smallest weight. Merge, and then we put the merged node of the two nodes into the q queue again, and loop until there is only one element root node left in q, so that a HuffmanTree is constructed.
③After the HuffmanTree is constructed, we can use the recursive function to traverse the HuffmanTree. The purpose of this is to print the encoding of each character. At the same time, we can also simulate the HuffmanTree tree to print the weight of each node, so You can see the internal construction of HuffmanTree more intuitively.
④The decoding process only needs to traverse the HuffmanTree tree according to the input ciphertext, starting from the root node and the first bit of the ciphertext, if the current bit is '0', the current node changes from the root node to the root node If the current bit is '1', then the current node will change from the root node to the right node of the root node, so until the root node has no left and right nodes, we will save the characters in this node After printing out, the decoding of a character is realized. If you want to continue decoding, you only need to update the current node back to the original root node.