You are given an undirected tree with n nodes, numbered from 0 to n - 1. It is represented by a 2D integer array edgesβββββββ of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
A node is called special if it is an endpoint of any diameter path of the tree.
Return a binary string s of length n, where s[i] = '1' if node i is special, and s[i] = '0' otherwise.
A diameter path of a tree is the longest simple path between any two nodes. A tree may have multiple diameter paths.
An endpoint of a path is the first or last node on that path.
Example 1:
Input:n = 3, edges = [[0,1],[1,2]]
Output:"101"
Explanation:
The diameter of this tree consists of 2 edges.
The only diameter path is the path from node 0 to node 2
The endpoints of this path are nodes 0 and 2, so they are special.
The diameter of this tree consists of 4 edges. There are 4 diameter paths:
The path from node 0 to node 4
The path from node 0 to node 5
The path from node 6 to node 4
The path from node 6 to node 5
The special nodes are nodes 0, 4, 5, 6, as they are endpoints in at least one diameter path.
Example 3:
βββββββ
Input:n = 2, edges = [[0,1]]
Output:"11"
Explanation:
The diameter of this tree consists of 1 edge.
The only diameter path is the path from node 0 to node 1
The endpoints of this path are nodes 0 and 1, so they are special.
Constraints:
2 <= n <= 105
edges.length == n - 1
edges[i] = [ai, bi]
0 <= ai, bi < n
The input is generated such that edges represents a valid tree.
Solutions
Solution 1: BFS
We first convert the array \(\text{edges}\) into an adjacency list representation of an undirected graph, where \(g[u]\) represents all nodes adjacent to node \(u\).
Next, we can use Breadth-First Search (BFS) to find the diameter endpoints of the tree. The specific steps are as follows:
Starting from any node (e.g., node \(0\)), use BFS to find the farthest node \(a\) from that node.
Starting from node \(a\), use BFS again to find the farthest node \(b\) from node \(a\), as well as the distance array \(\text{dist1}\) from node \(a\) to all other nodes.
Starting from node \(b\), use BFS to find the distance array \(\text{dist2}\) from node \(b\) to all other nodes.
The diameter length of the tree is \(\text{dist1}[b]\). For each node \(i\), if \(\text{dist1}[i]\) or \(\text{dist2}[i]\) equals the diameter length, then node \(i\) is a special node.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Where \(n\) is the number of nodes.