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

/*
typedef struct node {
	int val;
	int fin;
	struct node* fils[];
	int nbr_fils;
}Node, *PtNode, *Tree;

#include <stdio.h>
#include <stdlib.h>

int main(){
  int tmp;
  tmp = getchar();
  printf("%d\n",tmp);
  return 0;
}

 */

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;
  
  //(*ptr_tree)->fils = realloc(sizeof(struct node*)*nbr_fils);
  //(*ptr_tree)->fils[nbr_fils];
}

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)
{
  Node** node =  tab_ptr_tree[fl];
  for(int i=0;i<taille;i++)
  {
    if(node==NULL){
      node = malloc(sizeof(struct node));
      cons_tree(node,val[i]);continue;
      printf("%d",(*node)->val);
    }
    int trouve = -1;
    for(int j=0;j<(*node)->nbr_fils;j++)
    {
      if((*node)->fils[j]->val==val[i])
      {
	trouve=j;
	break;
      }
    }
    if(trouve == -1)
    {//ajouter fils
      (*node)->nbr_fils++;
      (*node)->fils = realloc((*node)->fils,((*node)->nbr_fils)*sizeof(struct node*));
      cons_tree(&((*node)->fils[((*node)->nbr_fils)-1]),val[i]);
      trouve = 0;
    }
    *node = (*node)->fils[trouve];
    if(i==taille-1)
      {
	(*node)->fin=1;
      }
  }
  //mettre fin à 1 pour le bon
  //if(i==taille-1)(*(tab_ptr_tree[fl]))->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)
    {
      if(val[0]<97)val[0]+=32;
      val[0]-=97;
      add(tab_ptr_tree,val,size(val),(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)
{
  
}