# Find farthest node from each node in Tree

Given a Tree, the task is to find the farthest node from each node to another node in this tree.
Example:

Input: Given Adjacency List of Below Tree: Output:
Farthest node from node 1: 6
Farthest node from node 2: 6
Farthest node from node 3: 6
Farthest node from node 4: 6
Farthest node from node 5: 1
Farthest node from node 6: 1

Input: Output:
Farthest node from node 1: 4
Farthest node from node 2: 7
Farthest node from node 3: 4
Farthest node from node 4: 7
Farthest node from node 5: 7
Farthest node from node 6: 4
Farthest node from node 7: 4

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:
First, we have to find two end vertices of the diameter and to find that, we will choose an arbitrary vertex and find the farthest node from this arbitrary vertex and this node will be one end of the diameter and then make it root to find farthest node from it, which will be the other end of diameter. Now for each node, the farthest node will be one of these two end vertices of the diameter of the tree.

Why it works?
Let x and y are the two end vertices of the diameter of the tree and a random vertex is u. Let the farthest vertex from u is v, not x or y. As v is the farthest from u then a new diameter will form having end vertices as x, v or y, v which has greater length but a tree has a unique length of the diameter, so it is not possible and the farthest vertex from u must be x or y.

Below is the implementation of above approach:

## C++

 `// C++ implementation to find the  ` `// farthest node from each vertex ` `// of the tree  ` ` `  `#include ` ` `  `using` `namespace` `std; ` ` `  `#define N 10000 ` ` `  `// Adjacency list to store edges ` `vector<``int``> adj[N]; ` ` `  `int` `lvl[N], dist1[N], dist2[N]; ` ` `  `// Add edge between  ` `// U and V in tree ` `void` `AddEdge(``int` `u, ``int` `v) ` `{ ` `    ``// Edge from U to V ` `    ``adj[u].push_back(v);  ` `     `  `    ``// Edge from V to U ` `    ``adj[v].push_back(u);  ` `} ` ` `  `int` `end1, end2, maxi; ` ` `  `// DFS to find the first  ` `// End Node of diameter ` `void` `findFirstEnd(``int` `u, ``int` `p) ` `{ ` `    ``// Calculating level of nodes ` `    ``lvl[u] = 1 + lvl[p]; ` `    ``if` `(lvl[u] > maxi) { ` `        ``maxi = lvl[u]; ` `        ``end1 = u; ` `    ``} ` `     `  `    ``for` `(``int` `i = 0; i < adj[u].size(); i++) { ` `         `  `        ``// Go in opposite  ` `        ``// direction of parent ` `        ``if` `(adj[u][i] != p) { ` `            ``findFirstEnd(adj[u][i], u); ` `        ``} ` `    ``} ` `} ` ` `  `// Function to clear the levels ` `// of the nodes ` `void` `clear(``int` `n) ` `{ ` `    ``// set all value of lvl[]  ` `    ``// to 0 for next dfs ` `    ``for` `(``int` `i = 0; i <= n; i++) { ` `        ``lvl[i] = 0; ` `    ``} ` `     `  `    ``// Set maximum with 0 ` `    ``maxi = 0; ` `    ``dist1 = dist2 = -1; ` `} ` ` `  `// DFS will calculate second  ` `// end of the diameter ` `void` `findSecondEnd(``int` `u, ``int` `p) ` `{ ` `    ``// Calculating level of nodes ` `    ``lvl[u] = 1 + lvl[p]; ` `    ``if` `(lvl[u] > maxi) { ` `        ``maxi = lvl[u]; ` `         `  `        ``// Store the node with  ` `        ``// maximum depth from end1 ` `        ``end2 = u; ` `    ``} ` ` `  `    ``for` `(``int` `i = 0; i < adj[u].size(); i++) { ` `        ``// Go in opposite  ` `        ``// direction of parent ` `        ``if` `(adj[u][i] != p) { ` `            ``findSecondEnd(adj[u][i], u); ` `        ``} ` `    ``} ` `} ` ` `  `// Function to find the distance ` `// of the farthest distant node ` `void` `findDistancefromFirst(``int` `u, ``int` `p) ` `{ ` `    ``// Storing distance from  ` `    ``// end1 to node u ` `    ``dist1[u] = 1 + dist1[p]; ` `    ``for` `(``int` `i = 0; i < adj[u].size(); i++) { ` `        ``if` `(adj[u][i] != p) { ` `            ``findDistancefromFirst(adj[u][i], u); ` `        ``} ` `    ``} ` `} ` ` `  `// Function to find the distance ` `// of nodes from second end of diameter ` `void` `findDistancefromSecond(``int` `u, ``int` `p) ` `{ ` `    ``// storing distance from end2 to node u ` `    ``dist2[u] = 1 + dist2[p]; ` `    ``for` `(``int` `i = 0; i < adj[u].size(); i++) { ` `        ``if` `(adj[u][i] != p) { ` `            ``findDistancefromSecond(adj[u][i], u); ` `        ``} ` `    ``} ` `} ` ` `  `void` `findNodes(){ ` `    ``int` `n = 5; ` ` `  `    ``// Joining Edge between two  ` `    ``// nodes of the tree ` `    ``AddEdge(1, 2); ` `    ``AddEdge(1, 3); ` `    ``AddEdge(3, 4); ` `    ``AddEdge(3, 5); ` ` `  `    ``// Find the one end of  ` `    ``// the diameter of tree ` `    ``findFirstEnd(1, 0); ` `    ``clear(n); ` `     `  `    ``// Find the other end  ` `    ``// of the diameter of tree ` `    ``findSecondEnd(end1, 0); ` ` `  `    ``// Find the distance  ` `    ``// to each node from end1 ` `    ``findDistancefromFirst(end1, 0); ` ` `  `    ``// Find the distance to  ` `    ``// each node from end2 ` `    ``findDistancefromSecond(end2, 0); ` ` `  `    ``for` `(``int` `i = 1; i <= n; i++) { ` `        ``int` `x = dist1[i]; ` `        ``int` `y = dist2[i]; ` `         `  `        ``// Comparing distance between ` `        ``// the two ends of diameter ` `        ``if` `(x >= y) { ` `            ``cout << end1 << ``' '``; ` `        ``} ` `        ``else` `{ ` `            ``cout << end2 << ``' '``; ` `        ``} ` `    ``} ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``// Function Call ` `    ``findNodes(); ` ` `  `    ``return` `0; ` `} `

Output:

```4 4 2 2 2
```

Time Complexity: O(V+E)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.