Hi, I'm a new member to this website but have always checked it for help when needed and the people here seemed helpful. Anyways, for my data structures class I need to encode and decode data using a huffman tree. What I have so far is a working Huffman tree with all the characters and their respective frequencies in the leaf nodes of my tree. Where I am stuck is in the encoding process. I understand that if you go left in your tree you need a 0, right is a 1, store the values in a string and so forth. But I wrote a recursive program just to see if I would get the correct values if i had a -1 for left and +1 for right and my values are all wrong except for the first one. Here is my code for it:
(output and level are initialized to 0 and the node passed is the root), I know I probly don't need level, but I just copied this quick from my print tree function.
void findleaf ( Node * & n, int level, int output)const
{
if (n) //n->left == NULL && n->right ==NULL)
{
int test = 0;
if (n->left == NULL && n->right ==NULL)
{
test = output;
cout << "Huff is : " << n->data << endl;
cout << "output for " << n->data << " is : " << output << endl;
}
output+=-1;
cout << "GOING LEFT (output) " << output<< endl;
findleaf (n->left, level-1, output);
output = test;
cout << "output is changed to " << output << endl;
cout << "Current location: " << n->data << endl;
output+=1;
cout << "GOING RIGHT (output) " << output<< endl;
findleaf (n->right, level+1, output);
output = test;
cout << "output changed to " << output << endl;
}
}
Thanks for any help!