נראה לי שזה יעבוד
(יש כאן הרבה קוד כפול, שאותו אפשר להוציא לפונקציות נפרדות או macro-ים, אבל נראה לי יותר ברור ככה) הפונקציה מציבה ב-d1 ו-d2 את המרחקים של node1 ו-node2 (בהתאמה) מהאב הקדמון המשותף הנמוך ביותר שהוא צאצא של root. אם node1 אינו צאצא של root הפונקציה מציבה ב-d1 את הערך INFINITY (הערך המקסימלי של int לצורך הענין). אם node1 הוא NULL הפונקציה לא נוגעת ב-d1. כנ"ל לגבי node2 ו-d2. הערך שמענין אותך אחרי ריצת הפונקציה הוא d1+d2.
void get_distance(node* root, node* node1, node* node2, int* d1, int* d2) { if (node1 == NULL && node2 == NULL) // both nodes were found return; if (root == NULL) { // we reached a dead-end if (d1 != NULL) *d1 = INFINITY; if (d2 != NULL) *d2 = INFINITY; return; } if (root == node1) { // we found node1, stop searching for it *d1 = 0; node1 = NULL; d1 = NULL; } if (root == node2) { // we found node2, stop searching for it *d2 = 0; node2 = NULL; d2 = NULL; } // look for unfound nodes in left subtree get_distance(root->left, node1, node2, d1, d2); // if both nodes were found, stop searching, we're done if ((d1 != NULL) && (*d1 < INFINITY) && (d2 != NULL) && (*d2 < INFINITY)) return; // if only node1 was found, stop searching for it, // but add increment distance by 1 (the distance from root to root->left) if ((d1 != NULL) && (*d1 < INFINITY)) { (*d1)++; node1 = NULL; d1 = NULL; } // if only node2 was found, stop searching for it, // but add increment distance by 1 (the distance from root to root->left) if ((d2 != NULL) && (*d2 < INFINITY)) { (*d2)++; node2 = NULL; d2 = NULL; } // look for unfound nodes in right subtree get_distance(root->right, node1, node2, d1, d2); // if both nodes were found, stop searching if ((d1 != NULL) && (*d1 < INFINITY) && (d2 != NULL) && (*d2 < INFINITY)) return; // if only node1 was found, stop searching for it, // but add increment distance by 1 (the distance from root to root->right) if ((d1 != NULL) && (*d1 < INFINITY)) { (*d1)++; node1 = NULL; d1 = NULL; } // if only node2 was found, stop searching for it, // but add increment distance by 1 (the distance from root to root->right) if ((d2 != NULL) && (*d2 < INFINITY)) { (*d2)++; node2 = NULL; d2 = NULL; } }