Given a Directed Tree consisting of N nodes, the task is to check if there exists a node in the given tree such that all other nodes are reachable by removing any directed edge from the Tree and adding another directed edge between any pair of nodes in the Tree at most floor(N/2) times. If there exists any such node, then print “Yes”. Otherwise, print “No”.
Input: N = 3
Remove the edge 2 -> 3 and insert an edge 1 -> 3.
Therefore, both the remaining nodes (2, 3) are now accessible from the node 1.
Count of operations required is 1, which is <= floor(3/2) (= 1).
Input: N = 5
Approach: The idea to solve this problem is based on the following observations:
- Every node should have at least one parent node, i.e. every node should have at least 1 indegree to make the tree accessible from the required node.
- It can be concluded that if every node has at least 1 indegree, then all other nodes can be accessed.
- Therefore, the task reduces to finding the number of nodes having 0 in-degrees and check if it is at most N / 2 or not.
Follow the steps below to solve the problem:
- Store the in-degree of every node in the tree in an auxiliary array A of size (N + 1).
- Initialize this array as A[key] = pair for all (key-value) pairs in the Map.
- Initialize a variable, say count as 0, to store the number of nodes having in-degree equal to 0.
- Traverse the array A and count the number of array elements with value 0 and store it in the variable count.
- After completing the above steps, if the value of count is at most floor(N/2), then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.