O(N) time    || C++/ Java
Get Sum and Count from left and right subtree Upfront for O(N) total time.\n# C++\n    int averageOfSubtree(TreeNode root) {\n        int cnt=0;\n        helper
Get **Sum** and **Count** from left and right subtree **Upfront for O(N) total time**.\n# C++\n    int averageOfSubtree(TreeNode* root) {\n        int cnt=0;\n        helper(root,cnt);\n        return cnt;\n    }\n    \n    pair<int,int> helper(TreeNode* root,int &cnt){\n        if(!root) return {0,0};\n        pair<int,int> l= helper(root->left,cnt);   //sum and count of nodes in left subtree with single call\n        pair<int,int> r= helper(root->right,cnt);  //sum and count of nodes in right subtree with single call\n        int sum= l.first+r.first+root->val;        //compute new sum \n        int count= l.second+r.second+1;            //compute new count of nodes\n        if(sum/count==root->val) cnt++;            //check if it is candidate or not\n        return {sum,count}; \n    }\n\t\n# Java\n    //user defined data-type\n\tclass data{\n        int first,second;\n        data(int x,int y){  first=x;  second=y; }\n    }\n    \n    public int averageOfSubtree(TreeNode root) {\n        int[] cnt= new int[1];\n        helper(root,cnt);\n        return cnt[0];\n    }\n    \n    data helper(TreeNode root,int[] cnt){\n        if(root==null) return new data(0,0);\n        data l= helper(root.left,cnt);   //sum and count of nodes in left subtree with single call\n        data r= helper(root.right,cnt);  //sum and count of nodes in right subtree with single call\n        int sum= l.first+r.first+root.val;   //get sum of subtree\n        int count= l.second+r.second+1;      //get count of nodes in this subtree\n        if(sum/count==root.val) cnt[0]++;    //check if it is candidate or not\n        return new data(sum,count); \n    }\n\t\n**Time** - O(N)\n**Space** - O(1) ignoring Recursion space
['C', 'Java']