Longest path in a tree

algorithmstrees

Given an undirected weighted tree with $n$ vertices, how can I design an algorithm that is $O (n^2)$ and other that is $O(n)$ for finding the longest path between two nodes in the tree (without repeating vertices or edges)?

Intuitively I think that running BFS or DFS twice might work for an $O(n^2)$ algorithm, and Dijkstra's algorithm for $O(n)$ an algorithm. However, I'm not sure how to show that this works (proof or pseudocode), or if it is actually correct.

Best Answer

This question may be more appropriate for CS Stack Exchange. Either way, I'll attempt to help out here.

  1. Yes, running BFS/DFS twice will work. We start with an arbitrary node, $u$ and run BFS/DFS to find the farthest node from it, say $v$. We then run BFS/DFS starting with $v$ and find the farthest node from it. This will output the longest path in the tree. Here is a question on CS Stack Exchange that addresses this (and a more efficient) method.

  2. Yes, Dijkstra's will work. Normally, Dijkstra's cannot be used for the longest path due to the possibilities of negative weight cycles, but it can be used here as we're dealing with trees. This is because the longest path between 2 nodes is the same as the shortest path between them (in other words, there is a unique path between any 2 nodes).

Hope that helped :)