karlangadas

TREE: 14TAD

Nov 14th, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "arbol.h"
  4.  
  5. int seEncuentra(TNode *node,TNode *p) {
  6.     if (node == NULL) return 0;
  7.     if (node == p) return 1;
  8.     return seEncuentra(node->left, p) || seEncuentra(node->right, p);
  9. }
  10. TNode primerAncestro(TNode *nodo, TNode *p,TNode *q) {
  11.     if (nodo == p  || nodo == q) return *nodo;
  12.  
  13.     int pEnlaIzq = seEncuentra(nodo->left, p);
  14.     int qEnlaIzq = seEncuentra(nodo->left, q);
  15.  
  16.     if (pEnlaIzq != qEnlaIzq) return *nodo;
  17.  
  18.     TNode *lado;
  19.     if (pEnlaIzq)   lado=nodo->left;
  20.     else    lado=nodo->right;
  21.  
  22.     return primerAncestro(lado, p, q);
  23. }
  24.  
  25. int main(){
  26.     TBinaryTree T;
  27.     TNode q;
  28.     init_tree(&T);
  29.     insert(&T,5);
  30.     insert(&T,3);
  31.     insert(&T,7);
  32.     insert(&T,1);
  33.     insert(&T,4);
  34.     insert(&T,6);
  35.     insert(&T,8);
  36.     insert(&T,0);
  37.     q=primerAncestro(T.root,T.root->left->right,T.root->right);
  38.     printf("%d\n",q.elem);
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment