![]() |
VOOZH | about |
Given a tree of N vertices and a positive integer K. The task is to find the count of nodes at a distance K for every node.
Examples:
Input: N = 5, K = 2, edges[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}}
Output: 2 1 1 2 2
Explanation:
- From node 1, there are 2 nodes that are at a distance of 2: node 4 and node 5.
- From node 2, there is 1 node that is at a distance of 2: node 3.
- From node 3, there is 1 node that is at a distance of 2: node 2.
- From node 4, there are 2 nodes that are at a distance of 2: node 1 and node 5.
- From node 5, there are 2 nodes that are at a distance of 2: node 1 and node 4.
Input: N = 5 K = 3, edges[][] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}
Output: 1 1 0 1 1
Approach: To solve the problem, follow the below idea:
The approach involves a depth-first search (DFS) traversal of the tree starting from each node to efficiently count the number of nodes at a distance K from all nodes.
Step-by-step algorithm:
Below is the implementation of the above approach:
1 2 2 1 3 1 4 2 5 2
Time complexity: O(N * K), where N is the number of nodes and K is the distance between the nodes.
Auxiliary Space: O(N * K)