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

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →

Heavy Light 2 White Falcon

White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr

View Solution →