Imagine you have n cities connected by roads forming a tree structure, where every city can reach every other city through a unique path. Your task is to analyze all possible connected subsets of cities and count how many have specific maximum distances.
You're given an array edges where edges[i] = [ui, vi] represents a bidirectional road between cities ui and vi. Since the cities form a tree, there are exactly n-1 edges.
A subtree is a subset of cities where:
- Every city in the subset can reach every other city in the subset
- The path between any two cities passes only through cities in the subset
Goal: For each distance d from 1 to n-1, count how many subtrees have a maximum distance of exactly d between any two cities in that subtree.
Return an array where the d-th element (1-indexed) represents the count of subtrees with maximum distance d.
Input & Output
Visualization
Time & Space Complexity
2^n subsets, each requiring O(n) operations for validation and diameter calculation
Adjacency list storage and BFS temporary arrays
Constraints
- 2 โค n โค 15
- edges.length == n - 1
-
edges[i].length == 2 - 1 โค ui, vi โค n
- The given input represents a valid tree