#include "stdio.h"
#include "string.h"
Typedef struct
{
Float weight; / * Used to store weights of each node * /
Unsigned int parent, lchild, rchild; / * Pointer to the kid nodes * /
} Htnode, * huffmantree; / * Dynamic allocation array, store Hawman Tree * /
Typedef char * * huffmancode;
HUFFMANTREE * HT = NULL;
HUFFMANCODE * HC = NULL;
CRTHUFFMANTREE (/ * huffmantree * ht, huffmancode * hc, * / float w [], int N)
{INT I, S1, S2, C, M, START, P;
CHAR * CD;
M = 2 * n-1;
* ht = (huffmantree) malloc ((M 1) * sizeof (htnode));
For (i = 1; i <= n; i )
{
(* HT) [i] .weight = w [i];
(* HT) [i] .parent = 0;
(* HT) [i] .lchild = 0;
(* HT) [i] .rchild = 0;
}
For (i = n 1; i <= m; i )
{
(* HT) [i] .weight = 0;
(* HT) [i] .parent = 0;
(* HT) [i] .lchild = 0;
(* HT) [i] .rchild = 0;
}
For (i = n 1; i <= m; i )
{
SELECT (/ * HT, * / I-1, & S1, & S2);
(* HT) [S1] .parent = i; (* HT) [S2] .parent = i;
(* HT) [i] .lchild = S1; (* HT) [i] .rchild = S2;
(* HT) [i] .weight = (* HT) [S1] .weight (* HT) [S2] .weight;
}
* hc = (huffmancode) malloc ((N 1) * sizeof (char *));
CD = (char *) Malloc (N * SizeOf (char));
CD [N-1] = '/ 0';
For (i = 1; i <= n; i )
{
START = N-1;
For (c = i, p = (* HT) [i] .parent; p! = 0; c = p, p = (* HT) [P] .parent)
IF ((* HT) [P] .lchild == C)
CD [- start] = '0';
ELSE CD [- start] = '1';
(* HC) [i] = (char *) Malloc ((N-START) * SIZEOF (CHAR));
STRCPY ((* HC) [i], & cd [start]);
Printf ("/ NTHE Code of the% D IS:", i);
Printf ("% s./n", (*HC) [I]);
Printf ("/ n ------------");
}
Free (CD);
}
SELECT (/ * huffmantree * HT, * / INT G, INT S1, INT S2)
{
INT J, K, M, N;
For (k = 1; k <= g; k )
{
IF ((* HT) [k] .parent == 0)
{
S1 = K;
Break;
}
}
For (j = 1; j <= g; j ) {
IF ((* HT) [J] .weight <(* HT) [K] .weight) && ((* HT) [j] .parent == 0))
S1 = j;
}
FOR (m = 1; m )
{
IF ((* HT) [M] .parent == 0) && (M! = S1))
{
S2 = m;
Break;
}
}
For (n = 1; n <= g; n )
{
IF ((* HT) [N] .weight <(* ht) [m] .weight) && ((* HT) [n] .parent == 0) && (n! = S1))
S2 = N;
}
}
Main ()
{
INT I, N;
Float W [20];
Printf ("Please Input the Number of the Datas: / N");
Scanf ("% d", & n);
For (i = 1; i <= n; i )
{Printf ("Please Input the Datas: / N");
Scanf ("% f", & w [i]);
}
CRTHUFFMANTREE (/ * HT, HC, * / W, N);
}