霍夫曼编码遍历

Huffman Code encoding traversal

本文关键字:遍历 编码 霍夫曼      更新时间:2023-10-16

我正在尝试对一个huffman树进行编码。我的树是正确的。我只需要弄清楚如何修复递归函数来正确创建表。谢谢你对我的帮助。

struct Code
{
   char letter;
   string code;
};
void createCode(BTree<Data>* root,string codeStr,vector<Code> &table)
{
   if (root->getRightChild() == NULL && root->getLeftChild() == NULL)
   {
      Code code;
      code.letter = root->getData().getLetter();
      code.code = codeStr;
      table.push_back(code);
   }
   else
   {
      createCode(root->getLeftChild(), codeStr.append("1"),table);
      createCode(root->getRightChild(), codeStr.append("0"),table);
   }
}

codeStr.append修改codeStr。因此,您正确地将codeStr + "1"传递给第一个递归调用,但将codeStr + "10"传递给第二个递归调用。因此,所有出现的"0"都以一个额外的"1"作为前缀。

尝试

createCode(root->getLeftChild(), codeStr + "1",table);
createCode(root->getRightChild(), codeStr + "0",table);