作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试对霍夫曼树进行编码。我的树是正确的。我只需要弄清楚如何修复我的递归函数以正确创建表。感谢我能得到的任何帮助。
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/
我是一名优秀的程序员,十分优秀!