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

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.


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;


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' ){
         //  printf("i was here");
           if (root->data != '\0'){
           //    printf("i was here");
                 printf("%c", root->data);
                 root = treeroot;
       else {
            if (root->data != '\0'){
                 printf("%c", root->data);
                root = treeroot;

                        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(temp.right==null && temp.left==null)

                        Solution in Python : 
In   Python3 :

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

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

View More Similar Problems

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →