Search code examples
c++huffman-code

How to store Huffman tree in file


I'm looking for a convenient way to store Huffman tree inside the file for further reading and decoding. Here is my Node structure:

struct Node
{
    char ch;
    int freq;
    Node *left, *right;

    Node(char symbol, int frequency, Node *left_Node, Node *right_Node) : ch(symbol),
                                                                          freq(frequency),
                                                                          left(left_Node),
                                                                          right(right_Node){};
};

I'm using pointers, so I'm not sure about how to store it. Here is the way how I'm building the tree:

void buildTree(std::priority_queue<Node *, std::vector<Node *>, comp> &pq, std::multimap<int, char> &freqsTable)
{

    for (auto pair : freqsTable)
    {
        Node *node = new Node(pair.second, pair.first, nullptr, nullptr);
        pq.push(node);
    }

    while (pq.size() != 1)
    {
        Node *left = pq.top();
        pq.pop();
        Node *right = pq.top();
        pq.pop();

        int freqsSum = left->freq + right->freq;
        Node *node = new Node('\0', freqsSum, left, right);
        pq.push(node);
    }
}

Solution

  • Traverse the tree recursively. At each node, send a 0 bit. At each leaf (pointers are nullptr), send a 1 bit, followed by the eight bits of the character.

    On the other end, read a bit, make a new node if it's a zero. If it's a 1, make a leaf with the next eight bits as a character. Proceed to the next empty pointer. The tree will naturally complete, so there is no need for an end marker in the description.