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)
- Find the shortest distance between any pair of two different good nodes
- Count nodes within K-distance from all nodes in a set
- Count of nodes which are at a distance X from root and leaves
- Find distance between two nodes of a Binary Tree
- Queries to find distance between two nodes of a Binary tree
- Find distance of nodes from root in a tree for multiple queries
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Print nodes at k distance from root
- Print all nodes at distance k from a given node
- Print all neighbour nodes within distance K
- Print all nodes that are at distance k from a leaf node
- Print nodes at k distance from root | Iterative
- Distance between two nodes of binary tree with node values from 1 to N
- Shortest distance between two nodes in an infinite binary tree
- Minimum distance to visit all the nodes of an undirected weighted tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.