![]() |
VOOZH | about |
Given a tree of N vertices, where a vertex can be colored or uncolored, the task is to determine for each vertex the maximum distance to any of the colored vertices. The task is to find the minimum value among all maximumdistances for vertices.
Input:
1
/ \
2 3
/ \ / \
4 5 6 7marked[] = {2, 6, 7}
Output: 2
Explanation: The maximum distance for each vertex are: [2,3,2,4,4,3,3], minimum is 2
Input:
1
/ \
2 3
/
4marked[] = {4}
Output: 0
Explanation: The maximum distance for each vertex are: [2,1,3,0], minimum is 0.
Approach: To solve the problem, follow the idea below:
The idea lies in the observation that only the marked vertex at the extreme positions will contribute to the answer because the vertex between them will have the minimum distance from marked vertex. Therefore, we just have to return the ceil of distance between two extreme vertex / 2. To find the distance between marked vertices at extreme ends find the distance of all vertices from the first vertex by BFS. Find the farthest marked node from the first node. Then from the farthest marked node found, using BFS find the other farthest marked node.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2 0
Time Complexity: O(N), where N is the number of nodes in the tree.
Auxiliary Space: O(N)