# Longest Cycle - Dynamic Programming / Tree

JavaScript solution:

``````const dfs = (graph, current, parent, longestPathTotal, longestPathFromLeafNode) => {
longestPathFromLeafNode[current] = 0;
longestPathTotal[current] = 0;
let longestPath = 0;
let secondLongestPath = 0;
for (const neighbor of graph[current]) {
if (neighbor != parent) {
longestPathTotal[current] = Math.max(longestPathTotal[current], dfs(graph, neighbor, current, longestPathTotal, longestPathFromLeafNode));
longestPathFromLeafNode[current] = Math.max(longestPathFromLeafNode[current], longestPathFromLeafNode[neighbor] + 1);
if (longestPathFromLeafNode[current] > longestPath) {
secondLongestPath = longestPath;
longestPath = longestPathFromLeafNode[current];
}
else if (longestPathFromLeafNode[current] > secondLongestPath) {
secondLongestPath = longestPathFromLeafNode[current];
}
}
}
longestPathTotal[current] = Math.max(longestPathTotal[current], longestPath + secondLongestPath);
return longestPathTotal[current];
}
const longestCycle = (n, edges) => {
const longestPathTotal = new Array(n + 1, 0)
const longestPathFromLeafNode = new Array(n+1, 0)

const graph = generateGraph(n, edges);
return dfs(graph, 1, 1, longestPathTotal, longestPathFromLeafNode) + 1;
}
``````

Hey, please why did we choose to construct an undirected graph over a directed graph?