gpt4 book ai didi

c++ - 霍夫曼码编码遍历

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:45 27 4
gpt4 key购买 nike

我正在尝试对霍夫曼树进行编码。我的树是正确的。我只需要弄清楚如何修复我的递归函数以正确创建表。感谢我能得到的任何帮助。

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);

关于c++ - 霍夫曼码编码遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com