karlangadas

Hoardwood Species

Nov 19th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef char* TElemento ;
  4. typedef struct nodo{
  5.     TElemento nombre;
  6.     int num;
  7.     struct nodo *left;
  8.     struct nodo *right;  
  9. }TNodo;
  10.  
  11. typedef struct arbol{
  12.     TNodo *root;
  13. }TArbol;
  14.  
  15. void tree_init(TArbol *);
  16. void tree_insert(TArbol *,TElemento);
  17. int tree_empty(TArbol *);
  18. void preorder(TNodo *);
  19.  
  20. void tree_init(TArbol *T){
  21.     T->root=NULL;
  22. }
  23.  
  24. int tree_empty(TArbol *T){
  25.     return (T->root==NULL);
  26. }
  27. void preorder(TNodo *N){
  28.     if (N==NULL)
  29.         return;
  30.     printf("%d\n",N->num);
  31.     preorder(N->left);
  32.     preorder(N->right);      
  33. }
  34.  
  35. void tree_insert(TArbol *T,TElemento elem){
  36.     TNodo *crt=T->root;
  37.     TNodo *ant;
  38.     int flag=-1;
  39.     while (crt){
  40.         printf("Raíz %s\n",T->root->nombre);
  41.         if (crt->nombre==elem){
  42.             printf("%s es igual a %s\n",crt->nombre,elem);
  43.             break;
  44.         }
  45.         else{
  46.             ant=crt;
  47.                 if (crt->nombre>elem){
  48.                 flag=1;
  49.                 crt=crt->right;
  50.             }
  51.             else{
  52.                 flag=0;
  53.                 crt=crt->left;
  54.             }
  55.         }
  56.     }
  57.    
  58.     if (crt==NULL){
  59.         printf("No se encontró %s en el arbol\n",elem);
  60.         TNodo *nuevo=malloc(sizeof(TNodo));
  61.         nuevo->nombre=elem;
  62.         nuevo->num=1;
  63.         nuevo->left=NULL;
  64.         nuevo->right=NULL;
  65.         if (crt==T->root){
  66.             printf("Es raíz %s\n",elem);
  67.             T->root=nuevo;
  68.         }
  69.         else{
  70.             if (flag)
  71.                 ant->right=nuevo;
  72.             else
  73.                 ant->left=nuevo;
  74.             printf("El hoja\n");
  75.         }
  76.         printf("%s aparece %d veces\n",elem,nuevo->num);  
  77.     }
  78.     else if (crt->nombre==elem){
  79.         printf("Se encontró %s en el arbol\n",elem);
  80.         (crt->num)++;
  81.         printf("%s aparece %d veces\n",elem,crt->num);
  82.     }
  83. }
  84. int main(){
  85.     int ncasos;
  86.     TArbol T;
  87.     char* s=malloc(sizeof(30));
  88.     scanf("%d\n",&ncasos);
  89.     tree_init(&T);
  90.     while(ncasos--){
  91.         while(gets(s)&&s[0]){
  92.             tree_insert(&T,s);
  93.             printf("Raíz %s\n",T.root->nombre);
  94.         }
  95.        
  96.         preorder(T.root);
  97.         printf("\n");
  98.     }
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment