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

  1. /* Esame 20 settembre '99 - parte 3 */
  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. void insert(int i, tree *t)
  22. {
  23.   if (*t==empty()) /* caso base: albero vuoto */
  24.     {
  25.       *t=(tree) malloc(sizeof(struct node));
  26.       (*t)->el=i;
  27.       (*t)->left=empty();
  28.       (*t)->right=empty();
  29.     }
  30.   else if (i<(*t)->el) /* passo induttivo, sottoalbero sinistro */
  31.     insert(i,&((*t)->left));
  32.   else if (i>(*t)->el) /* passo induttivo, sottoalbero destro */
  33.     insert(i,&((*t)->right));
  34.  
  35. /* nota bene: nel caso i==(*t)->el non fa nulla! */        
  36. }   
  37.  
  38.  
  39. void print(tree t)
  40. {
  41.   if (t!=empty()) /* se l'albero e` vuoto non stampo nulla */
  42.     {
  43.       print(t->left);
  44.       printf(" %d",t->el);
  45.       print(t->right);
  46.     }
  47. }
  48.  
  49.  
  50.  
  51. void Union1(tree t1, tree *t2)
  52. {
  53. if (t1!=empty())
  54.   {
  55.     insert(t1->el,t2);
  56.     Union1(t1->left,t2);
  57.     Union1(t1->right,t2);
  58.   }
  59. }
  60.  
  61.  
  62. void Union(tree t1, tree t2, tree * t3)
  63. {   Union1(t1,t3);
  64.     Union1(t2,t3);
  65.  }
  66.  
  67.  
  68.  
  69. int main(void)
  70. {
  71.   char fname[MAX];
  72.   tree t1=empty(),t2=empty();
  73.   tree t3 = empty();
  74.   FILE *fd=NULL;
  75.   int i;
  76.  
  77.   printf("Enter file name: ");
  78.   scanf("%s",fname);
  79.   if (fd=fopen(fname,"r"))
  80.     {
  81.       while (fscanf(fd,"%d",&i)==1 && i!=-1)
  82.       insert(i,&t1);
  83.       printf("Tree t1 from file %s: ",fname);
  84.       print(t1);
  85.       printf("\n");
  86.       while (fscanf(fd,"%d",&i)==1 && i !=-1)
  87.       insert(i,&t2);
  88.       printf("Tree t2 from file %s: ",fname);
  89.       print(t2);
  90.       printf("\n");
  91.       Union(t1,t2,&t3);
  92.       printf("Union: ");
  93.       print(t3);
  94.       printf("\n");   
  95.       fclose(fd);
  96.     }
  97.   else
  98.     printf("Error opening file %s\n",fname);
  99. }
  100.