Untitled
#include <bits/stdc++.h> #define pii pair<int, int> using namespace std; struct Node_Info { int height; int diameter; Node_Info(int h, int d) { this->height = h; this->diameter = d; } }; Node_Info dfs(vector<vector<int>> &adj, int node, int parent) { // base case: node is a leaf if (adj[node].size() == 0) return Node_Info(0, 0); int max_child_height = 0, second_max_child_height = 0; int max_child_diam = 0; for (int adjNode : adj[node]) { if (adjNode == parent) continue; Node_Info child_info = dfs(adj, adjNode, node); int child_height = child_info.height; int child_diam = child_info.diameter; if (child_height > max_child_height) { second_max_child_height = max_child_height; max_child_height = child_height; } else if (child_height > second_max_child_height) { second_max_child_height = child_height; } if (child_diam > max_child_diam) { max_child_diam = child_diam; } } int node_height = max_child_height + 1; int node_diam = max(max_child_diam, max_child_height + second_max_child_height); return Node_Info(node_height, node_diam); } int longestPath(vector<vector<int>> &edges, int n) { // Write your code here vector<vector<int>> adj(n); // create adj list for (vector<int> edge : edges) { int first_node = edge[0]; int second_node = edge[1]; adj[first_node].push_back(second_node); adj[second_node].push_back(first_node); } Node_Info ans = dfs(adj, 0, -1); return ans.diameter; }
Leave a Comment