home *** CD-ROM | disk | FTP | other *** search
/ ftp.disi.unige.it / 2015-02-11.ftp.disi.unige.it.tar / ftp.disi.unige.it / pub / .person / CataniaB / teach-act / testi-esami / labo-9.00 / parte3.c < prev    next >
C/C++ Source or Header  |  2000-09-20  |  1KB  |  98 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define MAX 30
  5.  
  6. /* TIPI */
  7.  
  8. typedef struct nodo *tree;
  9.  
  10. struct nodo
  11. {
  12.     tree dx;
  13.     tree sx;
  14.     int info;
  15. };
  16.  
  17.  
  18. /* PROTOTIPI */
  19.  
  20. tree empty(void);
  21. void insert( int, tree *);
  22. void print(tree);
  23. int leaves_number(tree);
  24.  
  25. /* FUNZIONI */
  26.  
  27.  
  28. tree empty()
  29. {
  30.     return NULL;
  31. }
  32.  
  33. void insert(int i,tree *t)
  34. {
  35.     if(i>=0)
  36.     {
  37.     
  38.     if((*t)==empty())
  39.     {
  40.         (*t)=(tree)malloc(sizeof(struct nodo));
  41.         (*t)->info=i;
  42.         (*t)->sx=empty();
  43.         (*t)->dx=empty();
  44.     }
  45.     else 
  46.       if(i<(*t)->info)
  47.         insert(i,&((*t)->sx));
  48.       else if(i>(*t)->info)
  49.         insert(i,&((*t)->dx));
  50. }
  51. }
  52.  
  53. int leaves_number(tree t)
  54. {
  55.     if(t==empty())
  56.         return 0;
  57.     else if(t->sx==empty() && t->dx==empty())
  58.         return 1;
  59.     else
  60.         return(leaves_number(t->sx)+leaves_number(t->dx));
  61. }
  62.  
  63. void print(tree t)
  64. {
  65.     if(t!=empty())
  66.     {
  67.         print(t->sx);
  68.         printf("%d  ",t->info);
  69.         print(t->dx);
  70.  
  71.     }
  72. }
  73.  
  74. /* MAIN */
  75.  
  76. void main()
  77. {
  78.     char nome[MAX];
  79.     tree t;
  80.     int i,n;
  81.     FILE *fd=NULL;
  82.     t=empty();
  83.  
  84.     printf("Dammi il nome del file:\n");
  85.     scanf("%s",nome);
  86.  
  87.     if(fd=fopen(nome,"r"))
  88.     {
  89.         while(fscanf(fd,"%d",&i) && i!=-1)
  90.             insert(i,&t);
  91.             
  92.         printf("%d\n",leaves_number(t));
  93.         fclose(fd);
  94.     }
  95.     else
  96.         printf("Errore di apertura del file");
  97. }
  98.