easy approach
\n\n# Code\n```\n\nclass Solution {\npublic:\nvector> g;\n\n  // DFS function to compute the maximum depth and update the diameter\n   int dfsDepth(int v, int i
\n\n# Code\n```\n\nclass Solution {\npublic:\nvector<vector<int>> g;\n\n  // DFS function to compute the maximum depth and update the diameter\n   int dfsDepth(int v, int i , unordered_set<int> &vis, int &res){\n        vis.insert(v);\n        int max1=0;\n        int max2=0;\n        for(auto nei: g[v]){\n            if(((1<<nei)&i) && vis.find(nei)==vis.end()){\n                int depth=1+dfsDepth(nei,i,vis,res);\n                if(depth>max1){\n                    max2=max1;  \n                    max1=depth;\n                }\n                //taking two max vaues and resturng the max out of thm\n                else if(depth>max2){\n                    max2=depth;\n                }\n            }\n        }\n        res=max(res,max1+max2);\n        return max1;\n    }\nint f(int i, int startNode) {\n    int diameter = 0;\n    // Calculate maximum depth and update diameter from startNode\n    unordered_set<int> subtree;\n    dfsDepth( startNode,i, subtree,diameter);\n    return diameter;\n}\n\n    // Function to find the first set bit in the binary representation of i\n    int frstSetBit(int i, int n) {\n        for (int j = 0; j < n; j++) {\n            if ((1 << j) & i) { // if bit j is set\n                return j;\n            }\n        }\n        return -1; // No set bit found\n    }\n\nbool validSubtree(int i, int n, int firstSetBit, int& mask) {\n\n    mask|=(1<<firstSetBit);\n        if (mask == i )\n        return true;\n\n    for (auto p : g[firstSetBit]) {\n        if ((i & (1 << p)) && !(mask & (1 << p))) { // twon thinf tocheck , valid tree part,and prev visisted\n            if(validSubtree(i, n, p,mask))\n            return true;\n        }\n    }\n    return false;\n}   \n\n\n\n    vector<int> countSubgraphsForEachDiameter(int n, std::vector<std::vector<int>>& edges) {\n        g.resize(n);\n        std::vector<int> ans(n-1, 0);\n\n        // Build the graph\n        for (auto p : edges) {\n            g[p[0] - 1].push_back(p[1] - 1);\n            g[p[1] - 1].push_back(p[0] - 1);\n        }\n\n        // Iterate over all possible subtrees represented by bitmasks\n        for (int i = 1; i < (1 << n); i++) { int firstSetBit = frstSetBit(i, n);\nint o=0;\n        if   (validSubtree(i, n,firstSetBit,o))// if this is a valid subtree, then find the largest diameter of this tree\n               {\n                int diameter = f(i, firstSetBit);\n                if (diameter > 0 && diameter < n) {\n                    ans[diameter - 1]++;\n                }\n            }\n        }\n\n        return ans;\n    }\n};
['Bit Manipulation', 'Depth-First Search', 'Bitmask', 'C++']