4

I am trying to do the encoding of a huffman tree. My tree is correct. I just need to figure out how to fix my recursive function to create the table properly. Thanks for any help I can receive.

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);
   }
}
user1266174
  • 111
  • 2
  • 11

1 Answers1

5

codeStr.append modifies codeStr. So you're passing correctly codeStr + "1" to the first recursive call, but codeStr + "10" to the second. As a result, all occurrences of "0" are prepended by an additional "1".

Try

createCode(root->getLeftChild(), codeStr + "1",table);
createCode(root->getRightChild(), codeStr + "0",table);
Henrik
  • 23,186
  • 6
  • 42
  • 92