Find Diameter Endpoints of a Tree Problem
Description
LeetCode Problem 3787.
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] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i 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.
Example 2:

Input: n = 7, edges = [[0,1],[1,2],[2,3],[3,4],[3,5],[1,6]]
Output: "1000111"
Explanation:
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 <= 10^5edges.length == n - 1edges[i] = [a_i, b_i]0 <= a_i, b_i < n- The input is generated such that
edgesrepresents a valid tree.
Solution
Approach: Three BFS Passes
All diameters of a tree pass through the same center, so once we know the two ends a and b of one diameter, every other diameter endpoint is at distance d (the diameter length) from a or from b.
- Run BFS from any node (say
0) and take the farthest nodea. It is always an end of some diameter. - Run BFS from
a. The farthest nodebis the other end, anddist1[b]is the diameter lengthd. Keep the distancesdist1froma. - Run BFS from
bto getdist2. - Node
iis special exactly whendist1[i] == dordist2[i] == d.
Complexity: O(n) time and O(n) extra space.
from collections import deque
class Solution:
def findSpecialNodes(self, n: int, edges: List[List[int]]) -> str:
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
def bfs(start: int):
dist = [-1] * n
dist[start] = 0
q = deque([start])
far = start
while q:
u = q.popleft()
if dist[u] > dist[far]:
far = u
for v in g[u]:
if dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
return far, dist
a, _ = bfs(0)
b, dist1 = bfs(a)
_, dist2 = bfs(b)
d = dist1[b]
ans = ["0"] * n
for i in range(n):
if dist1[i] == d or dist2[i] == d:
ans[i] = "1"
return "".join(ans)