data-structureshuffman-codehuffman-tree

How to count the bits in a Huffman tree


I am looking at the below Huffman tree, the corresponding frequency table and the subtotal table. That table calculates the subtotal bits. I want to know how to count the subtotal bits.

Image

In the first row of the subtotal table, code 0 maps to 15. I understand that because A has a count of 15. But why code 100 maps to 21? 100 represents the node B and B has a count of 7. I would think that for 100 we should calculate 7 + 15 = 22, but the table has 21. Why?


Solution

  • The column "Subtotal (#bits)" is the product of bit-length and count (frequency), and this represents how many bits in the encoded message are dedicated to represent all symbols B.

    So we can derive the numbers as follows:

    Symbol Count Code #bits in Code Subtotal (#bits)
    A 15 0 1 15 x 1 = 15
    B 7 100 3 7 x 3 = 21
    C 6 101 3 6 x 3 = 18
    D 6 110 3 6 x 3 = 18
    E 5 111 3 5 x 3 = 15
    TOTAL = 87

    87 is thus the length of the encoded message.