Given an integer k and a tree with n nodes. The task is to count the number of distinct pairs of vertices which have a distance of exactly k.
Input: k = 2
Input: k = 3
Approach: This problem can be solved using dynamic programming. For every vertex v of the tree, we calculate values d[v][lev] (0 <= lev <= k). This value indicates the number of vertices having distance lev from v. Note that d[v] = 0.
Then we calculate the answer. For any vertex v number of pairs will be a product of the number of vertices at level j – 1 and level k – j.
Below is the implementation of the above approach:
- Find distance between two nodes of a Binary Tree
- Queries to find distance between two nodes of a Binary tree
- Find distance from root to given node in a binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Querying the number of distinct colors in a subtree of a colored tree using BIT
- Possible edges of a tree for given diameter, height and vertices
- Maximize the sum of products of the degrees between any two vertices of the tree
- Minimum Operations to make value of all vertices of the tree Zero
- Queries to find whether a number has exactly four distinct factors or not
- Make a tree with n vertices , d diameter and at most vertex degree k
- Pairs with same Manhattan and Euclidean distance
- Given GCD G and LCM L, find number of possible pairs (a, b)
- All possible co-prime distinct element pairs within a range [L, R]
- Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n
- Find the cordinates of the fourth vertex of a rectangle with given 3 vertices
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.
Improved By : Mithun Kumar