我一直在尝试对霍夫曼树进行编码,但我无法弄清楚为什么我得到的二进制密钥都错了。树正确完成,因此我的二进制密钥方法会出现问题。
以下是我用于编码的代码:
void Tree::CreateBinary(Node *r)
{
if(r==nullptr)
{
cout << "empty Tree" << endl;
}
else
{
if (r->character != NULL)
{
Binary(root, "", r->character);
}
CreateBinary(r->LeftSon);
CreateBinary(r->RightSon);
}
}
void Tree::Binary(Node *r, string key, char character)
{
if (r->LeftSon == NULL && r->RightSon == NULL && r->character == character)
{
r->key = key;
cout << r->character << ": " << r->key << endl;
}
if (r->LeftSon != NULL)
{
if(r->LeftSon->character!=NULL && r->LeftSon->character!=character)
{
Binary(r->LeftSon, key, character);
}else
{
key = key + "0";
Binario(r->LeftSon, key, character);
}
}
if (r->RightSon != NULL)
{
key = key + "1";
Binary(r->RightSon, key, character);
}
}
当我尝试编码时,我得到了这些键:
I: 00
P: 01
E: 010
A: 0110
T: 01110
SPACE: 011110
S: 011111
答案 0 :(得分:2)
在此处查看您对key
的所作所为:
if (r->LeftSon != NULL)
{
if(r->LeftSon->character!=NULL && r->LeftSon->character!=character)
{
Binary(r->LeftSon, key, character);
}else
{
key = key + "0";
Binario(r->LeftSon, key, character);
}
}
if (r->RightSon != NULL)
{
key = key + "1";
Binary(r->RightSon, key, character);
}
在树的顶部,有一个左子,其字符为空,因此您将{0'追加到key
,然后使用该键探索正确的子树。
一个简单的解决方法:
Binario(r->LeftSon, key+"0", character);