Tree: Huffman Decoding


Problem Statement :


Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only the leaves will contain a letter and its frequency count. All other nodes will contain a null instead of a character, and the count of the frequency of all of it and its descendant characters.

For instance, consider the string ABRACADABRA. There are a total of  11 characters in the string. This number should match the count in the ultimately determined root of the tree. Our frequencies are A =  5, B = 2, R = 2, C =  1 and D = 1. The two smallest frequencies are for C  and D , both equal to 1, so we'll create a tree with them. The root node will contain the sum of the counts of its descendants, in this case 1 + 1  = 2 . The left node will be the first character encountered, C, and the right will contain D. Next we have 3 items with a character count of 2: the tree we just created, the character B and the character R. The tree came first, so it will go on the left of our new root node B .  will go on the right. Repeat until the tree is complete, then fill in the 1's and 0's for the edges. The finished graph looks like:


Input characters are only present in the leaves. Internal nodes have a character value of ϕ (NULL). We can determine that our values for characters are:

A - 0
B - 111
C - 1100
D - 1101
R - 10
Our Huffman encoded string is:

A B    R  A C     A D     A B    R  A
0 111 10 0 1100 0 1101 0 111 10 0
or
01111001100011010111100

To avoid ambiguity, Huffman encoding is a prefix free encoding technique. No codeword appears as a prefix of any other codeword.

To decode the encoded string, follow the zeros and ones to a leaf and return the character there.

You are given pointer to the root of the Huffman tree and a binary coded string to decode. You need to print the decoded string.


Function Description

Complete the function decode_huff in the editor below. It must return the decoded string.

decode_huff has the following parameters:

root: a reference to the root node of the Huffman tree
s: a Huffman encoded string


Input Format

There is one line of input containing the plain string, s. Background code creates the Huffman tree then passes the head node and the encoded string to the function.


Constraints


1   <=  | s |  <=  25


Output Format

Output the decoded string on a single line.



Solution :



title-img




                        Solution in C++ :

In   C++  :




/* 
The structure of the node is

typedef struct node
{
    int freq;
    char data;
    node * left;
    node * right;
    
}node;

*/


void decode_huff(node * root,string s)
{
   
   node *treeroot = root;
  // char *result = (char*)malloc(sizeof(char)*len);
    int i=0,k=0;
   while (s[i]!='\0'){
    //   printf("s[%d]%c\n", i, s[i]);
      
       if (s[i]== '1' ){
          
           root=root->right;
         //  printf("i was here");
           if (root->data != '\0'){
           //    printf("i was here");
                 printf("%c", root->data);
                 root = treeroot;
                 
                             
            }
          i++;
       }
       else {
          
           root=root->left;
            if (root->data != '\0'){
                 printf("%c", root->data);
                root = treeroot;
                 
                             
            }
          i++;
       }
       
       
       
       
       
   }
    
    
    
}
                    


                        Solution in Java :

In   Java :






/*  
   class Node
      public  int frequency; // the frequency of this tree
       public  char data;
       public  Node left, right;
    
*/ 

void decode(String S ,Node root)
    {
        Node temp=root;
        String ans="";
        for(int i=0;i<S.length();i++){
         //   System.out.println("er1");
            if(S.charAt(i)=='0')
                temp=temp.left;
            else
                temp=temp.right;
            if(temp.right==null && temp.left==null)
                {
                ans+=(temp.data);
                temp=root;
            }
        }
        System.out.println(ans);
       
    }
                    


                        Solution in Python : 
                            
In   Python3 :






"""class Node:
    def __init__(self, freq,data):
        self.freq= freq
        self.data=data
        self.left = None
        self.right = None
"""        
def decodeHuff(root, s):
    s=list(s)
    s=[int(i) for i in s]
    while len(s)!=0 :
        decodeHuf(root,s,root)



def decodeHuf(root, s,parent):
    
    
    if not (root.left or root.right) :
        print(root.data,end='')
        return
    if len(s)==0 :
        return
    
    x=s[0]
    del s[0]
    if x == 1 :
        decodeHuf(root.right,s,parent)
    else :
        decodeHuf(root.left,s,parent)
                    


View More Similar Problems

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →