Java | O(n) time | Beats 100%
java []\nclass Solution {\n    int ans;\n    public int averageOfSubtree(TreeNode root) {\n        ans=0;\n        traverse(root);\n        return ans;\n    }\n
``` java []\nclass Solution {\n    int ans;\n    public int averageOfSubtree(TreeNode root) {\n        ans=0;\n        traverse(root);\n        return ans;\n    }\n   \n    private int[] traverse(TreeNode root)\n    {\n        if(root==null)\n            return new int[]{0,0};\n        int[] left = traverse(root.left);\n        int[] right = traverse(root.right);\n        int sum = left[0]+right[0]+root.val;\n        int cnt = left[1]+right[1]+1;\n        if(sum/cnt==root.val){\n            ans++;\n        }\n        return new int[]{sum,cnt};\n    }\n}\n```
['Tree', 'Java']