c++ - 解码哈夫曼树

标签 c++ huffman-code

我正在尝试解码以下形式的哈夫曼树:

001A1C01E01B1D

我正在使用此处的实现:Efficient way of storing Huffman tree以上述形式对树进行编码并对其进行解码。

这是我的实现:

HuffmanNode* HuffmanTree::decodeTree(string tree, int idx) {
    cout << idx << endl;
    if (tree[idx] == '1') {
        idx += 2;
        return new HuffmanNode(tree[idx - 1]);
    }
    else {
        if (idx != tree.length() - 1) {
            idx++;
            HuffmanNode* leftChild = decodeTree(tree, idx);
            idx++;
            HuffmanNode* rightChild = decodeTree(tree, idx);
            return new HuffmanNode(leftChild, rightChild);
        }
        else
            return new HuffmanNode(tree[idx]);
    }
}

当函数展开时(在“return new HuffmanNode(tree[idx - 1]];”上),我在写一个位置时遇到了访问冲突,我希望最终的返回将是树,但经过进一步检查,情况似乎并非如此。谁能给我一些指示? (没有双关语意)

最佳答案

您的代码的问题是 idx 在递归运行中没有被修改。将其作为 int & 传递给函数:HuffmanNode* HuffmanTree::decodeTree(string tree, int &idx)

您的代码中还有一个错误,这使得它成为段错误:而不是

if (tree[idx] == '1') {
    idx += 2;
    return new HuffmanNode(tree[idx - 1]);
}

你应该有

if (tree[idx] == '1') {
    ++idx;
    return new HuffmanNode(tree[idx]);
}

另一个 1 被添加到第二个 block 中的索引:

idx++;
HuffmanNode* leftChild = decodeTree(tree, idx);
idx++;
HuffmanNode* rightChild = decodeTree(tree, idx);

此外,考虑做一件事,类似于您链接到的示例:传递对字符串迭代器(或 istringstream 或其他流)的引用,并且不传递索引: HuffmanNode* HuffmanTree::decodeTree(std::string::const_iterator &tree)

此外,如果树的格式正确,您不必像 if (idx != tree.length() - 1) 这样的检查。您仍然可以在函数的开头执行此操作以检查输入中的错误,并检查当前符号是 '0' 还是 '1'

关于c++ - 解码哈夫曼树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420277/

相关文章:

c++ - 霍夫曼代码 - 段错误 11

c++ - 条件表达式中的模数

c++ - 如何实现创建递归 lambda 并返回它的方法

C++ MSC_VER 与第三方库不匹配

algorithm - 构建哈夫曼树时如何选择优先级?

c++ - for_each 调用不适用于指针 vector

c++ - 是否存在删除了 ctor 的类有用的情况?

c++ - 在对C++程序进行反向工程时,如何将std::basic_string <char>转换为Rust可读的值?

c - 将一行数据存储到文件中

Java Huffman树代码 "Decode"方法不起作用