我正在尝试编写一个函数,它需要一个霍夫曼树和一个字符。然后它应该对角色进行编码并将其返回。编码哈夫曼二叉树
至今代码:
string encode(NodePtr root, char letter)
{
string encode_str; //a string which will store the encoded string
NodePtr tempNode = root; //Initialize a new Huffman to be used in this function
NodePtr tempLeft = root->left;
NodePtr tempRight = root->right;
//A while loop that goes on until we find the letter we want
while((tempLeft->letter != letter) || (tempRight->letter != letter))
{
if((tempRight->is_leaf()) && (tempRight->letter == letter)) //check if is leaf and is letter
{
encode_str = encode_str + '1';
}
else if ((tempLeft->is_leaf()) && (tempLeft->letter == letter)) //check if is leaf and is letter
{
encode_str = encode_str + '0';
}
else if ((tempRight->is_leaf()) && (tempRight->letter != letter)) //check if is leaf and is NOT letter
{
tempNode = root->left;
tempLeft = tempNode->left;
tempRight = tempNode->right;
encode_str = encode_str + '0';
}
else if ((tempLeft->is_leaf()) && (tempLeft->letter != letter)) //check if is leaf and is NOT letter
{
tempNode = root->right;
tempLeft = tempNode->left;
tempRight = tempNode->right;
encode_str = encode_str + '1';
}
}
return encode_str;
}
这至今还没有工作,调试并没有帮助我满意。任何人都可以帮助我,或者至少告诉我我的想法是否正确。
我以为root-> left或root-> right总是一片叶子?我基于此。所以我的计划是检查它是否是叶,看看这封信是否匹配。如果不是,它会“不落叶”的路径,并再次尝试。也许添加编码(tempNode,字母)如果!=字母? – user3265963
例如在维基百科显示有两个非叶孩子的节点:http://en.wikipedia.org/wiki/File:Huffman_tree_2.svg - 但您可能已经创建了一个具有您描述的特殊属性的树;在这种情况下,遵循我描述的调试步骤。 – slim
我以为我正在用tempNode = root->向右遍历树; 。那么新的tempnode会比之前的节点低一个节点。 – user3265963