1、Huffman树结构定义
#ifndef _huffman_tree_h
#define _huffman_tree_h
typedef struct huffman_tree_node
{
float weight;
int lchild, rchild, parent;
}huffman_tree_node, * huffman_tree;
typedef struct huffman_code
{
char ch;
char * code;
}huffman_code;
void create_huffman_tree( huffman_tree * root, float weight[], int n );
void huffman_encode( huffman_tree root, huffman_code * codes );
#endif
2、构造Huffman树
void create_huffman_tree( huffman_tree * root, float weight[], int n )
{
huffman_tree_node * p = NULL;
int s1, s2; // index
int i, n_nodes = 0;
if( n < 1 )
return;
n_nodes = 2 * n - 1;
p = ( huffman_tree_node * )malloc( sizeof( huffman_tree_node ) * n_nodes );
assert( p != NULL );
for( i = 0; i < n_nodes; ++i )
{
p[i].weight = i < n ? weight[i] : 0;
p[i].lchild = p[i].rchild = p[i].parent &