tree.c 1.98 KB
#include "tree.h"

void cons_tree(struct node ** ptr_tree, int val)
{
  *ptr_tree = malloc(sizeof(struct node));
  (*ptr_tree)->val = val;
  (*ptr_tree)->fin = 0;
  (*ptr_tree)->nbr_fils=0;
  (*ptr_tree)->fils = malloc(sizeof(struct node*));
  (*ptr_tree)->fils[0]=NULL;
}

void mk_empty_tree(struct node **ptr_tree)
{
  *ptr_tree = NULL;
}

int is_leaf(struct node *tree)
{
  return tree->fin||tree->fils[0]==NULL;
}

void add(struct node **tab_ptr_tree, char val[],int taille, int fl)
{
  if(tab_ptr_tree[fl]==NULL)cons_tree(&(tab_ptr_tree[fl]),val[0]+97);
  Node* noeudtest = tab_ptr_tree[fl];
  for(int i = 1;i<taille;i++)
    {
      int trouve = -1;
      for(int j=0;j<noeudtest->nbr_fils;j++)
	{
	  if(noeudtest->fils[j]->val==val[i])trouve=j;
	}
      if(trouve==-1)
	{	  
	  //ajouter lettre
	   noeudtest->nbr_fils++;
	   noeudtest->fils = realloc(noeudtest->fils,(noeudtest->nbr_fils)*sizeof(struct node*));
	   cons_tree(&(noeudtest->fils[(noeudtest->nbr_fils)-1]),val[i]);
	   trouve = 0;
	}
      
      noeudtest = noeudtest->fils[trouve];//on jump au noeud suivant
    }
  noeudtest->fin = 1;

}

int size(char val[])
{
  int cpt = 0;
  while(val[cpt]!='\0')
    {
      cpt++;
    }
  return cpt;
}


void load_tree(FILE *fp, struct node **tab_ptr_tree)
{
  //fl (first letter)
  char val[50];
  
  while(fscanf(fp, "%s",val)==1)
    {
      int taille = size(val);
      if(val[0]<97)val[0]+=32;
      val[0]-=97;
      add(tab_ptr_tree,val,taille,(int)val[0]);
    }

    //On peut tester la bonne ou mauvaise terminaison de la lecture
    if(feof(fp))    printf("Fin normal de lecture\n");
    if(ferror(fp))  printf("ERREUR de lecture\n");
}

void free_tree(struct node *ptr_tree)
{
  for(int i=0;i<ptr_tree->nbr_fils;i++)
  {
    if(ptr_tree->fils[i]->nbr_fils!=0)free_tree(ptr_tree->fils[i]);
    free(ptr_tree->fils[i]);
  }
  //free(ptr_tree);
}

void free_dico(struct node **tab_ptr_tree)
{
  for(int i=0;i<26;i++)
  {
    if(tab_ptr_tree[i]!=NULL)
    {
      free_tree(tab_ptr_tree[i]);
    }
  }
}