Huffman Compression 413
(* num ) ++;36
return ;37
}38
Tree _leafH elper (lc , num );39
Tree _leafH elper (rc , num );40
}41
42
int Tree_leaf ( Tr e eN ode * tn )43
{44
int num = 0;45
Tree _leafH elper (tn , & num ) ;46
return num ;47
}48
The following listing is part of the encode function after the code tree has been built.
// the linked list is no longer needed1
TreeNode * root = head -> tnptr ;2
free ( head );3
4
// build the code book5
// get the number of leaf nodes6
int numRow = Tree_l e af ( root );7
// get the tree ’s height8
int numCol = Tree _height ( root );9
// numCol should add 1 to a ccommoda t e the ending -110
numCol ++;11
// create a 2D array initializ e the codes to -112
int * * c o debook = malloc ( s i z e o f ( i nt *) * numRow ) ;13
int row ;14
for ( row = 0; row < numRow ; row ++)15
{16
codebook [ row ] = malloc ( s i z e o f ( i nt ) * numCol ) ;17
int col ;18
// ini tialize to -119
for ( col = 0; col < numCol ; col ++)20
{21
codebook [ row ][ col ] = -1;22
}23
}24
build CodeBoo k ( root , codebook );25
print CodeBoo k ( codebook , numRow );26
return 1;27
}28
The following listing shows the function buildCodeBook. It uses a recursive helper func-
tion to traverse the tree. When a leaf node is encountered, the character is stored. At line
14, the function uses the very first column (with index zero) to store the characters. The
code book codes start from the second index (i.e., index 1), which is passed as the fourth
argument to buildCodeBookHelper at line 44.
void buil dCod e Book Helpe r ( TreeNode * tn , i n t * * codebook ,1
int * row , in t col )2