哈夫曼编码的遍历方式

4

我正在尝试对哈夫曼树进行编码,我的树是正确的,我只需要找出如何修复递归函数以正确创建表格。感谢任何帮助我可以获得的。

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);
   }
}
1个回答

5

codeStr.append会修改codeStr。因此,您将codeStr + "1"正确地传递给第一个递归调用,但将codeStr + "10"传递给第二个递归调用。结果是,所有的"0"都被额外的"1"前缀。

尝试:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接