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 / parte1.c next >
C/C++ Source or Header  |  1999-09-23  |  1KB  |  71 lines

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