Find triplet such that number of nodes connecting these triplets is maximum
Given a Tree with N nodes, the task is to find a triplet of nodes (a, b, c) such that the number of nodes covered in the path connecting these nodes is maximum. (Count a node only once).
Input: N = 4
Output: (2, 3, 4)
(2, 3, 4) as path between (2, 3) covers nodes 2, 1, 3 and path between (3, 4) covers nodes 3, 1, 4. Hence all nodes are covered.
The Red Path in Tree denotes the path between 2 to 3 node which covers node 1, 2, 3. The green path denotes path between (3, 4) which covers node 3, 1, 4.
Input: N = 9
Edge Set :
Output: (6, 8, 1)
- One important point to notice is, two of the points in triplet must be the end of diameter of tree to cover maximum of the points.
- We need to find the longest length branch stick to the diameter.
- Now for 3rd node, apply DFS along with maintaining the depth for each node (DFS in all directions other than on the Diameter Path Selected ) to all the nodes present on the path of Diameter, the node which is at the farthest distance, would be considered as the 3rd node, as it covers the maximum node other than already covered by the Diameter. Diameter of Tree using DFS
Below is the implementation of the above approach:
(2, 3, 4)
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.