LC 3820 - Pythagorean Distance Nodes in a Tree
Approach This is simple questoin, traverse the tree to record the node distance for x, y, and z, and then check if the condition satisfy. Code class Solution { public: int specialNodes(int n, vector<vector<int>>& edges, int x, int y, int z) { vector<int> xs(n, -1); vector<int> ys(n, -1); vector<int> zs(n, -1); vector<vector<int>> adj(n); for(const auto& e: edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); } traverse(xs, adj, x, 0); traverse(ys, adj, y, 0); traverse(zs, adj, z, 0); int totalCnt = 0; for(int i = 0 ; i < n ; ++i) { long long a = xs[i]; long long b = ys[i]; long long c = zs[i]; long long m = max(max(a, b), c); if(a*a + b*b + c*c == 2*m*m) ++totalCnt; } return totalCnt; } void traverse(vector<int>& v, const vector<vector<int>>& adj, int root, int level) { if(v[root] != -1) return; v[root] = level; for(const auto& next: adj[root]){ traverse(v, adj, next, level+1); } } };