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:
- Total distinct pairs from two arrays such that second number can be obtained by inverting bits of first
- Find distance between two nodes of a Binary Tree
- Count of distinct graphs that can be formed with N vertices
- Queries to find distance between two nodes of a Binary tree
- Find distance from root to given node in 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
- Querying the number of distinct colors in a subtree of a colored tree using BIT
- Number of ways to paint a tree of N nodes with K distinct colors with given conditions
- Number of pairs with a given sum in a Binary Search Tree
- Find Next number having distinct digits from the given number N
- Queries to find whether a number has exactly four distinct factors or not
- 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
- Possible edges of a tree for given diameter, height and 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 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.