Distance in a Tree
You are given a tree with n vertices. A tree is a connected graph with no cycles. Distance of an array is the number of edges in the shortest path between u and v
You must count the number of distinct pairs of vertices (u, v) such that: distance(u, v) = k
Array edges: A 2D array of [u, v] pairs representing the undirected edges of the tree. Use this to build your 1-indexed adjacency list.
Also note: (u, v) and (v, u) are the same pair so count each pair only once.
Example 1:
Input: n = 5, k = 2, edges = [[1,2], [2,3], [3,4], [2,5]]
Output: 4
Explanation :
Tree:
1 | 2 / \ 3 5 | 4
Pairs at distance 2:
(1,3) (1,5) (3,5) (2,4)
Total: 4
Example 2:
Input: n = 5, k = 3, edges =[[1,2], [2,3], [3,4], [4,5]]
Output: 2
Explanation :
Tree: 1 — 2 — 3 — 4 — 5
Pairs with distance 3:
(1,4) (2,5)
Total: 2
Now Your Turn!
Pick the correct output for the given inputInput : n = 5, k = 2, edges =[[1,2], [1,3], [1,4], [1,5]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ n ≤ 50000
- 1 ≤ k ≤ 500
- 1 ≤ u, v ≤ n
- Graph is a Tree