I am trying to implement Huffman Coding and can't figure out how to encode a character using the trie without generating a lookup table. What I don't want to do is generate a map of each character to its encoded string of bits. I am trying to write a method which takes in the root of the Huffman trie and a character and spits out the correct code.
I have written the following code which doesn't work correctly. The problem is, I don't know how to get it to stop after getting the right result. It continues to add to the code after reaching the correct leaf node.
string lookup(HuffNode* root, char c, string prevCode, string direction){
string currentCode = prevCode + direction;
if(!root->isLeaf()){
currentCode = lookup(root->getLeft(), c, currentCode, "0");
currentCode = lookup(root->getRight(), c, currentCode, "1");
}else{
if(root->getChar() == c){
return currentCode;
}else{
return prevCode;
}
}
return currentCode;
}
string encodeChar(HuffNode* trie, char c){
return lookup(trie, c, "", "");
}
What would be the correct way to get the encoding of a character from a trie?