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:
- Check if a path exists in a tree with K vertices present or are at most at a distance D
- Find distance between two nodes of a Binary Tree
- Total distinct pairs from two arrays such that second number can be obtained by inverting bits of first
- Find distance from root to given node in a binary tree
- Find distance between two nodes in the given Binary tree for Q queries
- Queries to find distance between two nodes of a Binary tree
- Find distance of nodes from root in a tree for multiple queries
- Count of distinct graphs that can be formed with N vertices
- 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 sum of distance of a given node to every leaf node in a Weighted 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
- Minimum Operations to make value of all vertices of the tree Zero
- Maximize the sum of products of the degrees between any two vertices of the tree
- Possible edges of a tree for given diameter, height and vertices
- Make a tree with n vertices , d diameter and at most vertex degree k
- 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.