Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- //Juanjose Tenorio Peña
- typedef struct nodo{
- int valor;
- struct nodo* ptrHI;
- struct nodo* ptrHD;
- } TNodo;
- TNodo* aux;
- void crear_arbol(TNodo ** ptrRaiz);
- void inserta_nodo(TNodo **ptrRaiz, int valor);
- int isSubtree(TNodo*,TNodo*);
- int Identicos(TNodo*,TNodo*);
- void crear_arbol(TNodo ** ptrRaiz){
- *ptrRaiz = NULL;
- }
- void inserta_nodo(TNodo **ptrRaiz, int valor){
- TNodo *ptrHoja, *ptrRecorrido, *ptrPadre;
- ptrHoja = (TNodo*)malloc(sizeof(TNodo));
- ptrHoja->valor = valor;
- ptrHoja->ptrHI=ptrHoja->ptrHD=NULL;
- if(*ptrRaiz){
- ptrRecorrido = *ptrRaiz;
- ptrPadre = NULL;
- while (ptrRecorrido){
- ptrPadre = ptrRecorrido;
- if (ptrRecorrido->valor > valor)
- ptrRecorrido = ptrRecorrido->ptrHI;
- else
- ptrRecorrido = ptrRecorrido->ptrHD;
- }
- if (ptrPadre->valor > valor)
- ptrPadre->ptrHI = ptrHoja;
- else
- ptrPadre->ptrHD = ptrHoja;
- }
- else{
- *ptrRaiz = ptrHoja;
- }
- }
- /* Reviso si las raices de 2 arboles son iguales */
- int Identicos(TNodo * root1, TNodo *root2)
- {
- /* casos base */
- if(root1 == NULL && root2 == NULL)
- return 1;
- if(root1 == NULL || root2 == NULL)
- return 0;
- /* Reviso si los valores de las raices son iguales */
- return (root1->valor== root2->valor &&
- Identicos(root1->ptrHI, root2->ptrHI) &&
- Identicos(root1->ptrHD, root2->ptrHD) );
- }
- int isSubtree(TNodo*T,TNodo*S){
- /* casos base */
- if (S == NULL)
- return 1;
- if (T == NULL)
- return 0;
- /* Verifico el arbol con el actual nodo */
- if (Identicos(T, S))
- return 1;
- /* Si el valor de la raiz no concuerda, reviso en el subarbol izquierdo
- * y derecho */
- return isSubtree(T->ptrHI, S) ||
- isSubtree(T->ptrHD, S);
- }
- int main(int argc, char** argv) {
- TNodo *ptrRaiz;TNodo * ptr2;
- crear_arbol(&ptrRaiz);
- inserta_nodo(&ptrRaiz, 4);
- inserta_nodo(&ptrRaiz, 2);
- inserta_nodo(&ptrRaiz, 1);
- inserta_nodo(&ptrRaiz, 3);
- inserta_nodo(&ptrRaiz, 5);
- inserta_nodo(&ptr2, 10);
- inserta_nodo(&ptr2, 15);
- if( isSubtree(ptrRaiz, ptr2) )
- printf("El arbol 2 es subarbol del arbol 1");
- else
- printf("El arbol 2 no es subarbol del arbol 1");
- getchar();
- return (EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement