简体   繁体   English

如何将霍夫曼树存储在文件中

[英]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);
    }
}

Traverse the tree recursively.递归遍历树。 At each node, send a 0 bit.在每个节点,发送一个 0 位。 At each leaf (pointers are nullptr ), send a 1 bit, followed by the eight bits of the character.在每个叶子(指针为nullptr )处,发送一个 1 位,然后是字符的 8 位。

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.如果是 1,则用接下来的 8 位作为字符制作叶子。 Proceed to the next empty pointer.继续下一个空指针。 The tree will naturally complete, so there is no need for an end marker in the description.树会自然完成,因此描述中不需要结束标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM