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.
Input: Given Adjacency List of Below Tree:
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
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
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:
4 4 2 2 2
Time Complexity: O(V+E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V + E).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.