#include #include typedef struct Tree { int data; struct Tree *left, *right; }Tree; Tree* find(Tree *p, int data) { if(p != NULL) { if(p->data == data) return p; Tree *pom; pom = find(p->left, data); if(pom) return pom; pom = find(p->right, data); return pom; } return NULL; } int isNodePresent(Tree* root, Tree* node) { if (root == NULL) return 0; if (root == node) return 1; return isNodePresent(root->left, node) || isNodePresent(root->right, node); } int searchLCA(Tree* root, Tree** lca, Tree* x, Tree* y) { if (root == NULL) return 0; if (root == x || root == y) { *lca = root; return 1; } int left = searchLCA(root->left, lca, x, y); int right = searchLCA(root->right, lca, x, y); if (left && right) *lca = root; return left || right; } int findLCA(Tree* root, Tree* x, Tree* y) { Tree* lca = NULL; if (isNodePresent(root, y) && isNodePresent(root, x)) searchLCA(root, &lca, x, y); if (lca != NULL) { printf("NZP(%d,%d)=%d\n",x->data, y->data, lca->data); return 1; } else return 0; } Tree * create(int data) { Tree *pom; pom = (Tree*) malloc(sizeof(Tree)); pom->data = data; pom->left = pom->right = NULL; return pom; } Tree *form() { Tree* root, *pom; root = (Tree*) malloc(sizeof(Tree)); scanf("%d", &(root->data)); root->left = root->right = NULL; int parent, letfA, rightA; scanf("%d", &parent); while(parent != 0) { scanf("%d%d", &letfA, &rightA); pom = find(root, parent); if(letfA) pom->left = create(letfA); if(rightA) pom->right = create(rightA); scanf("%d", &parent); } return root; } void checkLCA(Tree *root) { int n, firstData, secondData; Tree *pom1, *pom2; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d%d", &firstData, &secondData); pom1 = find(root, firstData); pom2 = find(root, secondData); if(!findLCA(root, pom1, pom2)) printf("NZP(%d,%d)=NULL\n",firstData, secondData); } } int main() { Tree *root; root = form(); checkLCA(root); return 0; }