我正在嘗試編寫一個函數,它需要一個霍夫曼樹和一個字符。然後它應該對角色進行編碼並將其返回。編碼哈夫曼二叉樹
至今代碼:
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