[英]Decoding a Huffman Tree
我正在尝试解码以下形式的霍夫曼树:
001A1C01E01B1D
我正在使用一种在这里找到的实现: 一种存储霍夫曼树的有效方法,以上述形式对树进行编码并对其进行解码。
这是我的实现:
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)
您的代码中还有一个bug,这使其成为segfault:
if (tree[idx] == '1') {
idx += 2;
return new HuffmanNode(tree[idx - 1]);
}
你应该有
if (tree[idx] == '1') {
++idx;
return new HuffmanNode(tree[idx]);
}
第二个块中的索引被添加了另一个1
:
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'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.