EASY TO UNDERSTAND-DFS_APPROACH-with Explanation---BEATS 100%
Intuition\n Describe your first thoughts on how to solve this problem. \nStore the details of the subtrees like number of child nodes and the sum of all the val
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStore the details of the subtrees like number of child nodes and the sum of all the values child nodes for each node in a hashmap and use dfs to solve the problem.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N) N=number of nodes in the graph.\nfor traversing all the nodes in the graph.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\n    int result; // Counter to store the number of nodes meeting the condition.\n\n    // Helper function to perform DFS and calculate subtree sum and count.\n    pair<int, int> dfs(TreeNode* root, unordered_map<TreeNode*, pair<int, int>>& subtreeInfo) {\n        if (!root) {\n            return {0, 0};\n        }\n        \n        int sum = root->val;\n        int count = 1;\n        \n        auto leftInfo = dfs(root->left, subtreeInfo);\n        auto rightInfo = dfs(root->right, subtreeInfo);\n        \n        sum += leftInfo.first + rightInfo.first;\n        count += leftInfo.second + rightInfo.second;\n        \n        // Calculate the average for the current subtree rooted at \'root\'.\n        int average = sum / count;\n        \n        // Update the global result if the current node\'s value matches the average.\n        if (root->val == average) {\n            result++;\n        }\n        \n        // Store the sum and count of the current subtree in the map.\n        subtreeInfo[root] = {sum, count};\n        \n        return {sum, count};\n    }\n\npublic:\n    int averageOfSubtree(TreeNode* root) {\n        result = 0;\n        unordered_map<TreeNode*, pair<int, int>> subtreeInfo;\n        \n        dfs(root, subtreeInfo);\n        \n        return result;\n    }\n};\n\n\n\n```\n\n![image](https://assets.leetcode.com/users/images/9c6f9412-c860-47d6-9a2e-7fcf37ff3321_1686334926.180891.png)\n
['C++']