I am writing an huffman algorithm and I got problem with a collecting data in recursion function. It means I have a recursion function which generates codes from tree, but I would like to have them in array (this allow me processing data later). I wrote the function
void save_code(HuffNode** array, int pos, HuffNode *node, char * table, int depth)
{
if(node->left == NULL){
printf("%d - %c > ", pos, node->sign);
array[pos]->sign = node->sign;
strcpy(array[pos]->code, table);
puts(table);
// save to global table
}
else {
table[depth] = '0';
save_code(array, pos + 1, node->left, table, depth + 1);
table[depth] = '1';
save_code(array, pos + 1 , node->right, table, depth + 1);
}
}
The biggest problem I have with variable pos, I thought if I can increment the pos variable (like in loop for),so I would be able to save it in variable array at position pos. The whole program is here: https://github.com/mtczerwinski/algorithms/blob/master/huffman/huffman.c
Edit: I ask myself if global variable can solve a problem - after a few moments of coding - the answer is positive.
int pos = 0; // global variable
void save_code(HuffNode** array, HuffNode *node, char * table, int depth) {
if(node->left == NULL){
array[pos]->sign = node->sign;
strcpy(array[pos]->code, table);
pos++;
}
else {
table[depth] = '0';
save_code(array , node->left, table, depth + 1);
table[depth] = '1';
save_code(array, node->right, table, depth + 1);
}
}
I would like to ask how to collect data in recursion function between calls. What are other ways to solve problem like this one.