
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
TreeNode* lowestCommonAncestor(TreeNode* root, int n1, int n2) {
if (!root || root->val == n1 || root->val == n2) return root;
TreeNode* left = lowestCommonAncestor(root->left, n1, n2);
TreeNode* right = lowestCommonAncestor(root->right, n1, n2);
if (left && right) return root;
return left ? left : right;
}
int distanceFromRoot(TreeNode* root, int target, int distance) {
if (!root) return -1;
if (root->val == target) return distance;
int left = distanceFromRoot(root->left, target, distance + 1);
if (left != -1) return left;
return distanceFromRoot(root->right, target, distance + 1);
}
int distanceBetweenNodes(TreeNode* root, int n1, int n2) {
TreeNode* lca = lowestCommonAncestor(root, n1, n2);
int d1 = distanceFromRoot(lca, n1, 0);
int d2 = distanceFromRoot(lca, n2, 0);
return d1 + d2;
}
int main() {
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Distance between 4 and 5: %d\n", distanceBetweenNodes(root, 4, 5));
return 0;
}