User tree and user code

Source: Internet
Author: User

In the general data structure book, the author will generally introduce the Chapter of the tree (Huffman)

Tree and Harman encoding. User-Defined coding is an application of the User-Defined tree. He has a wide range of coding applications, such

In JPEG, the user can use the Harman encoding. First, we will introduce what is the husky tree. Also known as the optimal binary tree,

Is a binary tree with the shortest length of the weight path. The weighted path length of a tree is all the leaf nodes in the tree.

(If the root node is layer 0, the path length from the leaf node to the root node is

Is the number of layers of the leaf node ). The length of the tree's weighted path is marked as WPL = (W1 * l1 + W2 * l2 + W3 * L3 +... + wn * ln)

, N weighted wi (I =,... n) constitute a binary tree with N leaf nodes, and the path of the corresponding leaf node

The length is Li (I = 1, 2,... n ). It can be proved that the WPL of The Harman tree is the smallest.

Step:

1. For the given n weights {W1, W2, W3 ,..., WI ,..., wn} is the initial set of N Binary Trees. f = {T1, T2, T3 ,..., ti ,..., tn}, where each binary tree TI has only one root node with the weight of Wi, and its left and right subtree are empty. (For the convenience of computing on the computer, it is generally required to sort the weights in ascending order of Ti wi .)
2. In F, select the Left and Right Subtrees with the smallest root node weights as the newly constructed binary tree, the weight of the root node of the new binary tree is the sum of the weight of the root node of the left and right subtree.
3. Delete these two trees from F and add the new binary tree to the set F in ascending order.
4. Repeat steps 2 and 3 until there is only one binary tree in set F.

Simply put, if I have five characters, A, B, C, D, and E, the frequencies (I .e., weights) are 5, 4, 3, 2, 1, in the first step, we first take two minimum values as left and right Subtrees to construct a new tree, that is, take 1, 2 to form a new tree. The node is 1 + 2 = 3,

The dotted line is the newly generated node. In the second step, the newly generated node with the weight of 3 is placed in the remaining collection. Therefore, the set is changed to {5, 4, 3}. Then, based on the second step, the two smallest values form a new tree,

Then, create the Harman tree in sequence, for example:

Replace the values with the following characters:

Therefore, each character is encoded as follows: A-> 11, B-> 10, c-> 00, D-> 011, e-> 010

Hoffman encoding is a non-Prefix encoding. It will not be confused during decoding. It is mainly used in data compression, encryption and decryption, and other occasions.

 

C language code implementation:

/*-------------------------------------------------------------------------
* Name: source code encoded by Harman.
 * Date:   2011.04.16
* Author: Jeffrey Hill + jezze (Decoding part)
* Pass the test under Win-TC
* Implementation process: the user first constructs the User-Defined tree using the huffmantree () function, and then
* Starts from the bottom to the top (that is, starting from the node where the array serial number is zero ).
* Set the code to 0 on the left side of the parent node. If it is on the right side, set the code to 1. Finally, the generated encoding is output.
 *------------------------------------------------------------------------*/
#include <stdio.h>
#include<stdlib.h>
 
#define MAXBIT      100
#define MAXVALUE  10000
#define MAXLEAF     30
#define MAXNODE    MAXLEAF*2 -1
 
typedef struct 
{
    int bit[MAXBIT];
    int start;
} Hcodetype;/* encoding struct */
typedef struct
{
    int weight;
    int parent;
    int lchild;
    int rchild;
    int value;
} Hnodetype;/* node struct */
 
/* Construct a user-defined tree */
void HuffmanTree (HNodeType HuffNode[MAXNODE],  int n)
{ 
/* I, j: cyclic variable, M1, M2: Construct the weights of the two least weight nodes in the different PROCESS OF THE Harman tree,
X1 and X2: Construct the sequence numbers of the two least weight nodes in the array during different processes of the Harman tree. */
    int i, j, m1, m2, x1, x2;
/* Initialize and store the nodes in the huffnode [] array of the Harman tree */
    for (i=0; i<2*n-1; i++)
    {
Huffnode [I]. Weight = 0; // weight
        HuffNode[i].parent =-1;
        HuffNode[i].lchild =-1;
        HuffNode[i].rchild =-1;
Huffnode [I]. value = I; // actual value, which can be replaced with letters as needed
    } /* end for */
 
/* Enter the weight of N leaf nodes */
    for (i=0; i<n; i++)
    {
        printf ("Please input weight of leaf node %d: \n", i);
        scanf ("%d", &HuffNode[i].weight);
    } /* end for */
 
/* Construct the Huffman tree cyclically */
    for (i=0; i<n-1; i++)
    {
M1 = m2 = maxvalue;/* m1 and m2 store two nodes with no parent node and the minimum node weight */
        x1=x2=0;
/* Find the two nodes with the smallest weight and no parent node in all nodes and combine them into a binary tree */
        for (j=0; j<n+i; j++)
        {
            if (HuffNode[j].weight < m1 && HuffNode[j].parent==-1)
            {
                m2=m1; 
                x2=x1; 
                m1=HuffNode[j].weight;
                x1=j;
            }
            else if (HuffNode[j].weight < m2 && HuffNode[j].parent==-1)
            {
                m2=HuffNode[j].weight;
                x2=j;
            }
        } /* end for */
/* Set the parent node information of the two child nodes x1 and X2 found */
        HuffNode[x1].parent  = n+i;
        HuffNode[x2].parent  = n+i;
        HuffNode[n+i].weight = HuffNode[x1].weight + HuffNode[x2].weight;
        HuffNode[n+i].lchild = x1;
        HuffNode[n+i].rchild = x2;
 
Printf ("x1.weight and x2.weight in round % d: % d, % d \ n", I + 1, huffnode [X1]. weight, huffnode [X2]. weight);/* for testing */
        printf ("\n");
    } /* end for */
  /*  for(i=0;i<n+2;i++)
    {
        printf(" Parents:%d,lchild:%d,rchild:%d,value:%d,weight:%d\n",HuffNode[i].parent,HuffNode[i].lchild,HuffNode[i].rchild,HuffNode[i].value,HuffNode[i].weight);
} * // Test
} /* end HuffmanTree */
 
// Decoding
void decodeing(char string[],HNodeType Buf[],int Num)
{
  int i,tmp=0,code[1024];
  int m=2*Num-1;
  char *nump;
  char num[1024];
  for(i=0;i<strlen(string);i++)
  {
   if(string[i]==‘0‘)
  num[i]=0;        
  else
  num[i]=1;                    
  } 
  i=0;
  nump=&num[0];
  
 while(nump<(&num[strlen(string)]))
 {tmp=m-1;
  while((Buf[tmp].lchild!=-1)&&(Buf[tmp].rchild!=-1))
  {
  
   if(*nump==0)
   {
     tmp=Buf[tmp].lchild ;          
   } 
   else tmp=Buf[tmp].rchild;
   nump++;
        
  } 
  
  printf("%d",Buf[tmp].value);                                  
 }
 
  
}
 
 
int main(void)
{
    
Hnodetype huffnode [maxnode];/* defines a node struct array */
Hcodetype huffcode [maxleaf], CD;/* defines an array of encoding structures and a temporary variable to store information for encoding */
    int i, j, c, p, n;
    char pp[100];
    printf ("Please input n:\n");
    scanf ("%d", &n);
    HuffmanTree (HuffNode, n);
   
    
    for (i=0; i < n; i++)
    {
        cd.start = n-1;
        c = i;
        p = HuffNode[c].parent;
While (P! =-1)/* parent node exists */
        {
            if (HuffNode[p].lchild == c)
                cd.bit[cd.start] = 0;
            else
                cd.bit[cd.start] = 1;
CD. Start --;/* calculate the lower bit of encoding */
            c=p;                    
P = huffnode [C]. parent;/* set the next cycle condition */
        } /* end while */
        
/* Save the start bits of the Harman encoding and encoding for each leaf node */
        for (j=cd.start+1; j<n; j++)
        { HuffCode[i].bit[j] = cd.bit[j];}
        HuffCode[i].start = cd.start;
    } /* end for */
    
/* Output all the Haffman codes that have been saved */
    for (i=0; i<n; i++)
    {
        printf ("%d ‘s Huffman code is: ", i);
        for (j=HuffCode[i].start+1; j < n; j++)
        {
            printf ("%d", HuffCode[i].bit[j]);
        }
        printf(" start:%d",HuffCode[i].start);
       
        printf ("\n");
        
    }
/*    for(i=0;i<n;i++){
    for(j=0;j<n;j++)
        {
             printf ("%d", HuffCode[i].bit[j]);           
        }
        printf("\n");
        }*/
    printf("Decoding?Please Enter code:\n");
    scanf("%s",&pp);
decodeing(pp,HuffNode,n);
    getch();
    return 0;
}

User tree and user code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.