I've got to decompress a string that was encoded with a Huffman tree, but the code has variable length and not all inputs are in prefix, in which case I should print "invalid" and finish execution. The input consists of: number of different characters; characters and their codes; length of the encoded message; encoded message.
I'd ask a more specific question if I could, but I really don't know what's wrong, because I feel like everything is wrong.
A sample input would be: 6 e 11 m 101 x 100 l 011 p 010 o 00 18 111001110101001100
and it's output would be: "exemplo"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node_t
{
struct node_t *left, *right;
char* codigo;
unsigned char c;
} *node;
void decode(const char *s, node t)
{
node q = t;
while (*s)
{
if (*s++ == '0') q = q->left;
else q = q->right;
if (q->c) putchar(q->c), q = t;
}
putchar('\n');
}
struct node_t *insere(struct node_t *root, char x, char* h, int a)
{
if(!root)
{
root=(struct node_t*)malloc(sizeof(struct node_t));
root->c = x;
root->codigo=h;
root->left = NULL;
root->right = NULL;
return(root);
}
else
{
if(h[a]=='0')
{
if(root->left!=NULL)
{
printf("invalid\n");
exit(0);
}
root->left = insere(root->left,x, h, a+1);
}
else
{
if(h[a]=='1')
{
if(root->left!=NULL)
{
printf("invalid\n");
exit(0);
}
root->right = insere(root->right,x, h, a+1);
}
}
}
return(root);
}
void inorder(struct node_t *root)
{
if(root != NULL)
{
inorder(root->left);
free(root);
inorder(root->right);
}
return;
}
int main(void)
{
struct node_t *root;
root = NULL;
int i, N, M, k;
scanf("%d", &N);
char item, num[2*N];
for (i = 0; i < N; i++)
{
scanf("%c %s\n", &item, num);
root= insere(root, item, num, 0);
}
scanf("%d\n", &M);
char buf[M];
for (k=0; k<M; k++)
scanf ("%c", &buf[k]);
decode (buf, root);
inorder(root);
return 0;
}