C++ 0ms faster than 100% no need for bit mask, straightforward dfs
Iterates through all possible subtrees\n\nclass Solution {\npublic:\n  struct Node {\n    vector<int> children;\n  };\n  \n  vector<int> countSubgraphsForEachDi
Iterates through all possible subtrees\n```\nclass Solution {\npublic:\n  struct Node {\n    vector<int> children;\n  };\n  \n  vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) {\n    vector<int> result(n - 1, 0); // Will store final result\n    vector<Node> tree(n + 1); // Will contain the tree\n    vector<bool> visited(n + 1, false); // Useful for dfs later\n    \n    // Build the tree\n    for (auto& edge : edges) {\n      tree[edge[0]].children.push_back(edge[1]);\n      tree[edge[1]].children.push_back(edge[0]);\n    }\n    \n    // Find diameters for all subtrees rooted at node 1 (arbitrary choice for root)\n    computeDiameters(tree, 1, visited, result);\n    return result;\n  }\n  \n  struct SubTreeInfo {\n    int depth;\n    int diameter;\n    SubTreeInfo(int depth, int diameter) : depth(depth), diameter(diameter) {}\n  };\n  \n  vector<SubTreeInfo> computeDiameters(vector<Node>& tree, int nodeIdx, vector<bool>& visited,\n                                       vector<int>& result) {\n    auto& node = tree[nodeIdx];\n    vector<SubTreeInfo> subTrees; // Will store information for subtrees rooted at node\n    subTrees.push_back(SubTreeInfo(0, 0)); // First subtree just contains this node itself\n    visited[nodeIdx] = true; // Mark this node as visited\n    \n    for (int childIdx : node.children) {\n      if (visited[childIdx]) continue; // Ignore if this child is actually the parent\n      int numSubTrees = subTrees.size(); // Number of subtrees built so far\n      \n      // Get subtrees for this child\n      auto childSubTrees = computeDiameters(tree, childIdx, visited, result);\n      for (auto& childSubTree : childSubTrees) {\n        // Combine the child subtree with every subtree known so far\n        for (int i = 0; i < numSubTrees; ++i) {\n          auto& subTree = subTrees[i];\n          SubTreeInfo newSubTree(-1, -1);\n          \n          // Compute the depth of this new subtree\n          newSubTree.depth = max(subTree.depth, 1 + childSubTree.depth);\n          // Compute the diameter of this new subtree (Note: child can have bigger diameter too)\n          newSubTree.diameter = max(max(subTree.diameter, 1 + childSubTree.depth + \n                                        subTree.depth), childSubTree.diameter);\n          \n          // Populate the results array\n          result[newSubTree.diameter - 1]++;\n          // Record this subtree for future use by parent of the current node\n          subTrees.push_back(newSubTree);\n        }\n      }\n    }\n    return subTrees;\n  }\n};\n```
[]