Approach
Breadth-first search
For Find Diameter Endpoints of a Tree, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 44 lines of C++ from the credited upstream file find-diameter-endpoints-of-a-tree.cpp.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 string findSpecialNodes(int n, vector<vector<int>>& edges) {8 vector<vector<int>> adj(size(edges) + 1);9 for (const auto& e : edges) {10 adj[e[0]].emplace_back(e[1]);11 adj[e[1]].emplace_back(e[0]);12 }13 const auto& bfs = [&](int u) {14 vector<bool> lookup(size(adj));15 lookup[u] = true;16 vector<int> q = {u}, new_q;17 while (!empty(q)) {18 new_q.clear();19 for (const auto& u : q) {20 for (const auto& v : adj[u]) {21 if (lookup[v]) {22 continue;23 }24 lookup[v] = true;25 new_q.emplace_back(v);26 }27 }28 swap(q, new_q);29 }30 return new_q;31 };32 33 string result(n, '0');34 const auto& far = bfs(0);35 for (const auto& u : far) {36 result[u] = '1';37 }38 for (const auto& u : bfs(far[0])) {39 result[u] = '1';40 }41 return result;42 }43};44