Tree: Huffman Decoding

  • + 0 comments

    C++

    void decode_huff(node * root, string s) 
    {
        string result = "";
        node * currNode = root;
        auto it = s.begin();
        
        while (it != s.end())
        {
            // Read s and traverse until we reach a leaf.
            while (currNode->data == '\0')
            {
                if (*it == '0')
                {
                    currNode = currNode->left;
                }
                else if (*it == '1')
                {
                    currNode = currNode->right;
                }
                else 
                {
                    cout << "Error";
                }
                
                it++;
            }
            
            // Leaf. Get letter and reset.
            result += currNode->data;
            currNode = root;
        }
        
        cout << result;
    }