Advertisement
Guest User

Untitled

a guest
Feb 1st, 2015
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int max3(int, int, int);
  5.  
  6. struct tree_node {
  7.     int dato;
  8.     struct tree_node *sx;
  9.     struct tree_node *dx;
  10. } nodo;
  11.  
  12. typedef struct tree_node *Tree;
  13.  
  14. int ricerca(Tree t, int k) {
  15.     if (t==NULL)
  16.         return 0;
  17.     else
  18.         return (t->dato==k) || (ricerca(t->sx, k)) || (ricerca(t->dx, k));
  19. }
  20.  
  21. int get_max(Tree t) {
  22.     int max_sx, max_dx;
  23.     /*Caso base: albero vuoto*/
  24.     if (t==NULL)
  25.         return -1;
  26.     max_sx = get_max(t->sx);
  27.     max_dx = get_max(t->dx);
  28.     return max3(max_sx, max_dx, t->dato);
  29. }
  30.  
  31. int max3(int a, int b, int c) {
  32.     if (a > b)
  33.       if (c > a) return c;
  34.       else return a;
  35.  
  36.    else
  37.       if (c > b) return c;
  38.       else return b;
  39. }
  40.  
  41. int uguali(Tree t1, Tree t2) {
  42.     if (t1==NULL && t2==NULL)
  43.         return 1;
  44.     else
  45.         if (t1==NULL || t2== NULL)
  46.             return 0;
  47.     return ((t1->dato==t2->dato) && uguali(t1->sx, t2->sx) && uguali(t1->dx, t2->dx));
  48. }
  49.  
  50. Tree creaAlbero() {
  51.     Tree t = (Tree)malloc(sizeof(nodo));
  52.     int n;
  53.     t->dato = n;
  54.     t->sx = NULL;
  55.     t->dx = NULL;
  56.     char c;
  57.     printf("Inserisci il dato del nodo: ");
  58.     scanf("%d", &n);
  59.     printf("Vuoi continuare a inserire altri dati? Y/N\n");
  60.     scanf("%c", &c);
  61.     if (c!='Y')
  62.         return t;
  63.     else {
  64.         t->sx = creaAlbero();
  65.         t->dx = creaAlbero();
  66.     }
  67. }
  68.  
  69.  
  70. main() {
  71.     Tree t = creaAlbero();
  72.     printf("Nell'albero è presente il valore 4? ");
  73.     if (ricerca(t, 4)!=0)
  74.         printf("TRUE\n");
  75.     else
  76.         printf("FALSE\n");
  77.     printf("Il valore più alto inserito nell'albero e' %d", get_max(t));
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement