Search code examples
c++binary-treehuffman-code

Decoding Huffman Tree


I am implementing a function that takes in a tree and an encoded string. Example:

decode(*Huffmantree, "10010101010")

I want this function to return decoded string for the encoded string in the input relative to the Huffman tree input.

The code I have so far:

string decode(NodePtr root, string encoded_str)
{
    string temp = "";
    for (int i = 0 ; i < encoded_str.size() ; i++)
    {
        if (root->is_leaf() == true)
        {
            temp[i] = root->letter;
            //cout << root->letter;
        }
        if (root->left != NULL)
        {
            encoded_str.
        }
        if(root->right != NULL)
        {

        }
    }
    return temp;
}

I am having trouble implementing what happens when either left or right is not NULL, i.e. when I have to continue to the next node.

Any ideas?

edit:

string decode(NodePtr root, string encoded_str)
{
    string temp = "";
    int i;
    for( i = 0 ; i < encoded_str.size() ; i++)
    {

    if(root == NULL)
    {
        cout<<"error in string"<<endl;
        return temp;
        //cout<<root->letter;
    }
    temp[i] = root->letter;
    if(encoded_str[i] == '0')
    {
        root = root->left;
    }
    else
    {
        root = root->right;
    }
    }
//    for (int i = 0 ; i < temp.size(); i++)
//    {
//        cout<<temp[i];
//    }
//    cout<<endl;
    temp[i]='/0';
    return temp;
}

Solution

  • Following may help:

    string decode(NodePtr root, string encoded_str)
    {
        string res = "";
        NodePtr node = root;
        for (int i = 0; i != encoded_str.size(); ++i)
        {
            if (encoded_str[i] == '0') { // left child
                node = node->left;
            } else { // rigth child
                assert(encoded_str[i] == '1');
                node = node->right;
            }
            if (node->is_leaf() == true)
            {
                res += node->letter;
                node = root;
            }
        }
        return res;
    }