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.99 / parte4.c < prev    next >
C/C++ Source or Header  |  1999-10-10  |  2KB  |  95 lines

  1. /* Esame 20 settembre '99  parte 4 */
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. #define MAX 30
  7. #define FALSE 0
  8. #define TRUE 1
  9.  
  10. typedef char bool;
  11.  
  12. typedef struct node *tree;
  13.  
  14. struct node
  15. {
  16.   int el;
  17.   tree left,right;
  18. };
  19.  
  20. tree empty()
  21. {   
  22.    return NULL;
  23. }   
  24.  
  25. void insert(int i, tree *t)
  26. {
  27.   if (*t==empty()) /* caso base: albero vuoto */
  28.     {
  29.       *t=(tree) malloc(sizeof(struct node));
  30.       (*t)->el=i;
  31.       (*t)->left=empty();
  32.       (*t)->right=empty();
  33.     }
  34.   else if (i<(*t)->el) /* passo induttivo, sottoalbero sinistro */
  35.     insert(i,&((*t)->left));
  36.   else if (i>(*t)->el) /* passo induttivo, sottoalbero destro */
  37.     insert(i,&((*t)->right));
  38.  
  39. /* nota bene: nel caso i==(*t)->el non fa nulla! */        
  40. }   
  41.  
  42.  
  43. void print(tree t)
  44. {
  45.   if (t!=NULL) /* se l'albero e` vuoto non stampo nulla */
  46.     {
  47.       print(t->left);
  48.       printf(" %d",t->el);
  49.       print(t->right);
  50.     }
  51. }
  52.  
  53.  
  54. int nodes_number(tree t)
  55. {
  56.     if(t==empty()) 
  57.     {
  58.         return(0);
  59.     }
  60.     if((t->left==empty()) && (t->right==NULL))
  61.     {
  62.         return 1;
  63.     }
  64.     else
  65.     {
  66.         return(1+nodes_number(t->left)+nodes_number(t->right));
  67.     }
  68. }
  69.  
  70.  
  71. int main(void)
  72. {
  73.   char fname[MAX];
  74.   tree t1=NULL,t2=NULL, t=NULL;
  75.   FILE *fd=NULL;
  76.   int i;
  77.  
  78.   printf("Enter file name: ");
  79.   scanf("%s",fname);
  80.   if (fd=fopen(fname,"r"))
  81.     {
  82.       while (fscanf(fd,"%d",&i)==1 && i!=-1)
  83.       insert(i,&t1);
  84.       printf("Tree t1 from file %s: ",fname);
  85.       print(t1);
  86.       printf("\n");
  87.       printf("Number of nodes: ");
  88.       i=nodes_number(t1);
  89.       printf("%d\n\n",i);
  90.       fclose(fd);
  91.     }
  92.   else
  93.     printf("Error opening file %s\n",fname);
  94. }
  95.