Given a connected acyclic graph with N nodes and N-1 edges, find out the pair of nodes that are at even distance from each other.
Input: 3 1 2 2 3 Output: 1 Explanation: 1 / 2 / 3 Input: 5 1 2 2 3 1 4 4 5 Output: 4
- Assume a graph is having 6 levels (0 to 5) level 0, 2, 4 are at even distance but level 1, 3, 5 are also at even distance as their difference is 2 which is even so we have to take care of both the conditions i.e count both levels even and odd.
- The given problem can be solved by performing dfs traversal
- Choose any source node as root and perform dfs traversal and maintain the visited
array for performing dfs and dist array to calculate distance from the root
- now traverse the distaance array and keep count of even level and odd level
- Calcluate total as ((even_count * (even_count-1)) + (odd_count * (odd_count-1))/2
Below is the implementataion of above approach:
Time Complexity: 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.
- Find the shortest distance between any pair of two different good nodes
- Count nodes within K-distance from all nodes in a set
- Print even positioned nodes of even levels in level order of the given binary tree
- Print levels with odd number of nodes and even number of nodes
- Count of nodes which are at a distance X from root and leaves
- Count pairs of leaf nodes in a Binary Tree which are at most K distance apart
- Queries to find distance between two nodes of a Binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Find distance of nodes from root in a tree for multiple queries
- Find distance between two nodes in the given Binary tree for Q queries
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- Find distance between two nodes of a Binary Tree
- Count the nodes in the given tree whose weight is even
- Count the nodes in the given tree whose weight is even parity
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count of all prime weight nodes between given nodes in the given Tree
- Maximize count of nodes disconnected from all other nodes in a Graph
- Print nodes at k distance from root
- Print all nodes that are at distance k from a leaf node
- Print all nodes at distance k from a given node
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.