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, . 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 :


                            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++;
       }
       
       
       
       
       
   }
    
    
    
}





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);
       
    }





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)


# Enter your code here. Read input from STDIN. Print output to STDOUT
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)
        
    
        
	#Enter Your Code Here
                        




View More Similar Problems

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →