Advertisement
Guest User

Leonardo

a guest
Feb 1st, 2015
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.77 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.     t->sx = NULL;
  53.     t->dx = NULL;
  54.     char c;
  55.     printf("Inserisci il dato del nodo: ");
  56.     scanf(" %d", &t->dato);
  57.     printf("Vuoi continuare a inserire altri dati? [Y/N] ");
  58.     scanf(" %c", &c);
  59.     if (c!='Y')
  60.         return t;
  61.     else {
  62.         t->sx = creaAlbero();
  63.         t->dx = creaAlbero();
  64.         return t; //devi aggiungere questa linea così che la tua funzione possa sempre terminare
  65.     }
  66. }
  67.  
  68.  
  69. int main() {
  70.     Tree t = creaAlbero();
  71.     printf("Nell'albero è pr4esente il valore 4? ");
  72.    
  73.     if (ricerca(t, 4)!=0)
  74.         printf("TRUE\n");
  75.     else
  76.         printf("FALSE\n");
  77.    
  78.     printf("Il valore più alto inserito nell'albero e' %d\n", get_max(t));
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement