I am facing a problem related to dfs in C programming. I need to find Count Nodes Equal to Average of Subtree. Unfortunately, I did not find enough guides on c, so I am asking for help. This code still doesn't work and gives wrong results, so I'd appreciate it if you could point out my mistakes.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int ans=0;
int dfs(struct TreeNode* root){
if (root == NULL) return 0,0;
int left,left_count = dfs(root->left);
int right,right_count = dfs(root->right);
int totalSum = left+right+root->val;
int count = left_count + right_count + 1;
if (totalSum/count == root->val) ans++;
return totalSum,count;
}
int averageOfSubtree(struct TreeNode* root){
dfs(root);
return ans;
}
I've modified this code many times, but I've never gotten to a working code. At the output, I get the data, but it is incorrect (thanks in advance).