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
- 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
- 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
- Queries to find whether a number has exactly four distinct factors or not
- Minimum Operations to make value of all vertices of the tree Zero
- 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
- 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)
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