Find Diameter Endpoints of a Tree

You are given an undirected tree with n nodes labeled from 0 to n - 1. The tree is described by a 2D integer array edges of size n - 1, where edges[i] = [ai, bi] represents an undirected edge between nodes ai and bi.

A diameter path of a tree is a simple path (no repeated nodes) that has the maximum possible number of edges among all paths in the tree.

A tree can have more than one diameter path.

A node is considered special if it appears as an endpoint (either start or end node) of at least one diameter path.

Return a binary string s of length n, where:

  • s[i] = '1' if node i is special
  • s[i] = '0' otherwise

Example 1:

Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]

Output: "10001"

Explanation:

The tree forms a straight chain: 0 - 1 - 2 - 3 - 4.

The diameter path is from node 0 to node 4.

The endpoints are nodes 0 and 4, so they are special.

Example 2:

Input: n = 6, edges = [[0,1],[1,2],[2,3],[2,4],[4,5]]

Output: "100001"

Explanation:

  • The longest simple path (diameter) has 4 edges.
  • The only diameter path is: 0 → 1 → 2 → 4 → 5 (length = 4).
  • So the only diameter endpoints are 0 and 5.
  • Hence the binary string marks only indices 0 and 5 as 1 → "100001".

Now Your Turn!

Pick the correct output for the given input

Input: n = 4, edges = [[0,1],[1,2],[1,3]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= n <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • The given input always forms a valid tree (connected and acyclic).

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
string findSpecialNodes(int n, vector<vector<int>>& edges) {
// Your code goes here
}
};
Test Case

Input:

Edges
N