霍夫曼编码树

时间:2014-02-17 13:37:10

标签: c++ huffman-code

我正在尝试构建一个霍夫曼编码树。

主要

int main()
{
    // Read frequency table and build Huffman tree.
    NodePtr huffman = build_tree();
    print_tree(huffman);

    // Free the allocated memory.
    free_memory(huffman);

    return 0;
}

输入应该在表格中:

number of letters
"letter" number of occurrences
"letter2" number of occurrences

到目前为止,我还没有工作。什么想法可能是错的?

build_tree函数:

NodePtr build_tree()
{
    int characters;//number of characters
    cin >> characters;
    char letter;
    int freq;
    HuffmanPriorityQueue queue;
    NodePtr p;
    for (int i = 0 ; i < characters; i++)
    {
        cin >> letter;
        cin >> freq;
        NodePtr temp = new HuffmanNode(freq, letter);
        queue.push(temp);
    }
    for (int i = 0 ; i < characters - 1 ; i++)
    {
        NodePtr a = queue.top();
        queue.pop();
        NodePtr b = queue.top();
        NodePtr p = new HuffmanNode (a->frequency + b->frequency, NULL);
        queue.push(p);
    }
    return p;
}

打印功能:提供了哪个,所以我认为它是正确的。

void print_tree(NodePtr root, int indent = 0, string prefix = "")
{
    // External nodes are not printed.
    if (root == NULL) {
        return;
    }

    char letter = ' ';
    if (root->is_leaf()) {
        letter = root->letter;
    }

    cout << string(indent, ' ') << prefix << "(" << letter << " [" << root->frequency << "]";
    if (root->is_leaf()) {
        cout << ")" << endl;
    } else {
        cout << endl;
        // Print left and right subtrees with the appropriate prefix, and
        // increased indent (by INDENT_SIZE).
        print_tree(root->left, indent + INDENT_SIZE, "0");
        print_tree(root->right, indent + INDENT_SIZE, "1");
        cout << string(indent, ' ') << ")" << endl;
    }
}

1 个答案:

答案 0 :(得分:3)

你有几个问题:

  • 永远不会分配外部NodePtr p
  • pop
  • 没有NodePtr b
  • 新节点未引用其子ab
  • 你没有归还根。

以下可能有所帮助:

for (int i = 0 ; i < characters - 1 ; i++)
{
    NodePtr a = queue.top();
    queue.pop();
    NodePtr b = queue.top();
    queue.pop();
    NodePtr p = new HuffmanNode (a, b); // The new node has two children `a` and `b`.
    queue.push(p);
}
return queue.top(); // Return root.