Advertisement
juanjo12x

Construir_Arbol_Preorden_Inorden

Jun 13th, 2014
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct nodo{
  5.     int valor;
  6.     struct nodo* ptrHI;
  7.     struct nodo* ptrHD;
  8. } TNodo;
  9. int preIndex = 0;
  10. void crear_arbol(TNodo ** ptrRaiz);
  11. void pre_orden(TNodo * ptrRaiz);
  12. void en_orden(TNodo * ptrRaiz);
  13. int search(int arr[], int strt, int end, int value);
  14. TNodo* Construir_Arbol(int[],int[],int ,int);
  15. void crear_arbol(TNodo ** ptrRaiz){
  16.     *ptrRaiz = NULL;
  17. }
  18. void pre_orden(TNodo * ptrRaiz){
  19.     if (ptrRaiz){
  20.         printf("%d -", ptrRaiz->valor);
  21.         pre_orden(ptrRaiz->ptrHI);
  22.         pre_orden(ptrRaiz->ptrHD);
  23.     }
  24. }
  25. void en_orden(TNodo * ptrRaiz){
  26.     if (ptrRaiz){        
  27.         en_orden(ptrRaiz->ptrHI);
  28.         printf("%d -", ptrRaiz->valor);
  29.         en_orden(ptrRaiz->ptrHD);        
  30.     }
  31. }
  32.  
  33.  
  34. /* Funcion para encontrar el indice de un arreglo arr[start...end]
  35.    La funcion asume que el valor esta en el arreglo in[] */
  36. int search(int arr[], int strt, int end, int value)
  37. {
  38.   int i;
  39.   for(i = strt; i <= end; i++)
  40.   {
  41.     if(arr[i] == value)
  42.       return i;
  43.   }
  44. }
  45.  
  46. TNodo* Construir_Arbol(int in[], int pre[], int inStrt, int inEnd)
  47. {
  48.  
  49.  
  50.   if(inStrt > inEnd)
  51.      return NULL;
  52.   /* Elige el nodo actual del arreglo preorden usando el pre-indice
  53.     e incremento pre-indice */
  54.  
  55.   TNodo *tNode;
  56.   tNode = (TNodo*)malloc(sizeof(TNodo));
  57.   tNode->valor = pre[preIndex];
  58.   tNode->ptrHI = NULL;
  59.   tNode->ptrHD = NULL;
  60.   preIndex++;
  61.  
  62.   /* Si este nodo no tiene hijos, retorno */
  63.   if(inStrt == inEnd)
  64.     return tNode;
  65.  
  66.   /* Else find the index of this node in Inorder traversal */
  67.   int inIndex = search(in, inStrt, inEnd, tNode->valor);
  68.  
  69.   /* Using index in Inorder traversal, construct left and
  70.      right subtress */
  71.   tNode->ptrHI = Construir_Arbol(in, pre, inStrt, inIndex-1);
  72.   tNode->ptrHD = Construir_Arbol(in, pre, inIndex+1, inEnd);
  73.  
  74.   return tNode;
  75. }
  76. int main(int argc, char** argv) {
  77.   TNodo *ptrRaiz;
  78.   int n=5;
  79.     int in[] = {1,2,3,4,5};
  80.     int pre[] = {4,2,1,3,5};
  81.     crear_arbol(&ptrRaiz);
  82.     ptrRaiz=Construir_Arbol(in,pre,0,n-1);
  83.     pre_orden(ptrRaiz);
  84.     printf("\n");
  85.     en_orden(ptrRaiz);
  86.    
  87.     return (EXIT_SUCCESS);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement