Advertisement
Dany1858

Esercizio Alberi binari

Jan 9th, 2015
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. /*Memorizzare i dati immessi in un albero binario in modo che l etichetta di un
  2. qualsiasi nodo sia maggiore di tutti i valorei del suo sottoalbero sinistro, e
  3. minore di tutti quelli del suo sottoalbero destro*/
  4.  
  5. #include <stdio.h>
  6. #include <malloc.h>
  7.  
  8. struct nodo{
  9.        int inf;
  10.        struct nodo *left;
  11.        struct nodo *right;
  12. };
  13.  
  14. struct nodo *creaAlb(void);
  15. struct nodo *creaNodo(struct nodo *, int);
  16. void anticipato(struct nodo *);
  17.  
  18. main()
  19. {
  20.   struct nodo *radice;
  21.  
  22.   radice=creaAlb();
  23.  
  24.   printf("\nVISITA IN ORDINE ANTICIPATO\n\n");
  25.   anticipato(radice);
  26.  
  27.   printf("\n\nPremere un tasto per uscire..");
  28.   getchar(); getchar(); return 0;
  29. }
  30.  
  31. struct nodo *creaAlb(void)
  32. {
  33.        struct nodo *p=NULL;
  34.        int x=-1;
  35.        
  36.        while(x!=0){
  37.           printf("\nInserire elemento, 0 per uscire\t");
  38.           scanf("%d", &x);
  39.           if(x!=0) p=creaNodo(p, x);}
  40.        return p;
  41. }
  42.  
  43. struct nodo *creaNodo(struct nodo *p, int val)
  44. {
  45.        if(p==NULL){
  46.           p=(struct nodo*)malloc(sizeof(struct nodo));
  47.           p->inf=val;
  48.           p->left=NULL;
  49.           p->right=NULL;
  50.        }
  51.        else{
  52.           if(val>p->inf) p->right=creaNodo(p->right, val);
  53.           else if(val<p->inf) p->left=creaNodo(p->left, val);
  54.              else{
  55.                  printf("\nElemento gia' presente!\t");
  56.                  getchar();}
  57.        }
  58.        return p;
  59. }
  60.  
  61. void anticipato(struct nodo *p)
  62. {
  63.      if(p!=NULL){
  64.          printf("%d    ", p->inf);
  65.          if(p->left!=NULL){
  66.          printf("\n<- ");
  67.          anticipato(p->left);}
  68.          if(p->right!=NULL){
  69.             printf("\n\t-> ");
  70.             anticipato(p->right);}}
  71.      else printf("\nAlbero vuoto!!");
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement