1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include "allinclude.h"
bool findPath(BiTree T, TElemType target, Stack& path);
BiTree CommAncestor(BiTree T, TElemType a, TElemType b) { if(!T || T->data == a || T->data == b) { return NULL; }
BiTree parent = NULL; SElemType temp; temp.ptr = NULL; Stack S1,S2,Sq,Sp; InitStack(S1); InitStack(S2); InitStack(Sq); InitStack(Sp);
if(!findPath(T,a,Sp) || !findPath(T,b,Sq)) return NULL;
while (!StackEmpty(Sp)) { Pop(Sp,temp); Push(S1,temp); }
while (!StackEmpty(Sq)) { Pop(Sq,temp); Push(S2,temp); }
SElemType temp1,temp2; temp1.ptr = temp2.ptr = NULL; do{ parent = temp1.ptr;
GetTop(S1,temp); if(temp.ptr->data == a) break; GetTop(S2,temp); if(temp.ptr->data == b) break;
Pop(S1,temp1); Pop(S2,temp2); }while(temp1.ptr == temp2.ptr);
return parent; }
bool findPath(BiTree T, TElemType target, Stack& path) { if (!T) { return FALSE; } SElemType temp; temp.ptr = T; Push(path,temp); if(T->data == target) { return TRUE; } if((T->lchild && findPath(T->lchild,target,path)) || (T->rchild && findPath(T->rchild,target,path))) { return true; }
Pop(path,temp); return FALSE;
}
|