#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Structure for adjacency list node
typedef struct Node {
int val;
struct Node* next;
} Node;
Node* graph[MAX];
int diameter = 0;
// Add edge to undirected graph
void addEdge(int u, int v) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = v;
node->next = graph[u];
graph[u] = node;
node = (Node*)malloc(sizeof(Node));
node->val = u;
node->next = graph[v];
graph[v] = node;
}
// DFS to find longest path down from node and update diameter
int dfs(int u, int parent) {
int max1 = 0, max2 = 0; // top two longest child paths
for (Node* curr = graph[u]; curr != NULL; curr = curr->next) {
int v = curr->val;
if (v == parent) continue; // avoid going back
int length = dfs(v, u) + 1; // path length from child
if (length > max1) {
max2 = max1;
max1 = length;
} else if (length > max2) {
max2 = length;
}
}
if (max1 + max2 > diameter) {
diameter = max1 + max2; // update global diameter
}
return max1; // return longest path down
}
int main() {
// Build tree from example
addEdge(1, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(3, 5);
dfs(1, -1);
printf("Diameter length = %d\n", diameter);
return 0;
}
for (Node* curr = graph[u]; curr != NULL; curr = curr->next) {
Traverse all children of current node u
if (v == parent) continue;
Skip the parent node to avoid revisiting
int length = dfs(v, u) + 1;
Recursively find longest path down from child v and add edge
if (length > max1) { max2 = max1; max1 = length; } else if (length > max2) { max2 = length; }
Keep track of top two longest child paths
if (max1 + max2 > diameter) { diameter = max1 + max2; }
Update global diameter if current node's paths form longer path
Return longest path down from current node