[LeetCode] Count Nodes Equal to Average of Subtree

2265. Count Nodes Equal to Average of Subtree

Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.

Note:

  • The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
  • A subtree of root is a tree consisting of root and all of its descendants.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int res = 0;
pair<int, int> helper(TreeNode* node) {
if(!node) return {0, 0};
auto [ls, lc] = helper(node->left);
auto [rs, rc] = helper(node->right);
auto s = ls + rs + node->val;
auto c = lc + rc + 1;
if(s/c == node->val) res++;
return {s,c};
}
public:
int averageOfSubtree(TreeNode* root) {
helper(root);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/14/PS/LeetCode/count-nodes-equal-to-average-of-subtree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.