Simple Clean Code With Description C++
\n# Approach\n We want to use dfs to traverse the tree and while traversing we want to know the average at the each node and when we backtrack we will use the a
\n# Approach\n We want to use dfs to traverse the tree and while traversing we want to know the average at the each node and when we backtrack we will use the averages of already calculated averages of the children of the node and use them to calculate the average of the root node.\n\n We carry forward the values sum and the no of nodes with the help of value pair to help us calulate the average and to compare the average is equal to value of the root. If it is equal we increase the count by 1.\n\n# Complexity\n- Time complexity:\n Time complexity of this approach(D.F.S) is O(n) where n is the number of nodes in the given tree.\n\n    Upvote if you find it helpful.\n\n\n# Code\n```\nclass Solution {\npublic:\nint count = 0;\n    int averageOfSubtree(TreeNode* root) {\n        average(root);\n        return count;\n    }\nint avg,sum,no_of_nodes;\n   pair<int,int> average(TreeNode* root){\n       if (root == NULL){\n           return make_pair(0, 0);\n       }\n        pair<int,int> left = average(root->left);\n        pair<int,int> right = average(root->right);\n        sum = (left.first + right.first + root->val);\n        no_of_nodes = (left.second + right.second + 1);\n        avg = sum/(no_of_nodes);\n        if (root->val == avg){\n            count++;\n       }\n       return make_pair(sum, no_of_nodes);\n    }\n};\n```
['Tree', 'Depth-First Search', 'C++']