title: Huffman decoding in c using tree
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>A sample input would be:
          6
          e 11
          m 101
          x 100
          l 011
          p 010
          o 00
          18
          111001110101001100</p>
  
  <p>and it's output would be: 
          "exemplo"</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  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-&gt;left;
          else q = q-&gt;right;
  
          if (q-&gt;c) putchar(q-&gt;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-&gt;c = x;
          root-&gt;codigo=h;
          root-&gt;left = NULL;
          root-&gt;right = NULL;
          return(root);
      }
      else
      {
          if(h[a]=='0')
          {
              if(root-&gt;left!=NULL)
              {
                  printf("invalid\n");
                  exit(0);
               }
              root-&gt;left = insere(root-&gt;left,x, h, a+1);
          }
          else
          {
              if(h[a]=='1')
              {
                  if(root-&gt;left!=NULL)
                  {
                      printf("invalid\n");
                      exit(0);
                  }
                  root-&gt;right = insere(root-&gt;right,x, h, a+1);
              }
          }
      }
      return(root);
  }
  
  void inorder(struct node_t *root)
  
  {
      if(root != NULL)
      {
          inorder(root-&gt;left);
          free(root);
          inorder(root-&gt;right);
      }
      return;
  }
  
  int main(void)
  {
      struct node_t *root;
      root = NULL;
      int i, N, M, k;
      scanf("%d", &amp;N);
      char item, num[2*N];
      for (i = 0; i &lt; N; i++)
      {
          scanf("%c %s\n", &amp;item, num);
          root= insere(root, item, num, 0);
      }
      scanf("%d\n", &amp;M);
      char buf[M];
      for (k=0; k&lt;M; k++)
          scanf ("%c", &amp;buf[k]);
      decode (buf, root);
      inorder(root);
      return 0;
  }
  </code></pre>