Skip to content

Commit 2a51c20

Browse files
authored
Create count-nodes-equal-to-average-of-subtree.cpp
1 parent b863302 commit 2a51c20

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
private:
14+
int counter = 0;
15+
public:
16+
std::pair<int, int> subtreeSum(TreeNode* root) {
17+
int current_sum = root->val;
18+
int current_size = 1;
19+
if (root->left != NULL) {
20+
auto [subtree_size_l, subtree_sum_l] = subtreeSum(root->left);
21+
current_sum += subtree_sum_l;
22+
current_size += subtree_size_l;
23+
}
24+
if (root->right != NULL) {
25+
auto [subtree_size_r, subtree_sum_r] = subtreeSum(root->right);
26+
current_sum += subtree_sum_r;
27+
current_size += subtree_size_r;
28+
}
29+
30+
if (current_sum / current_size == root->val) {
31+
counter += 1;
32+
}
33+
34+
return std::make_pair(current_size, current_sum);
35+
}
36+
int averageOfSubtree(TreeNode* root) {
37+
subtreeSum(root);
38+
return counter;
39+
}
40+
};

0 commit comments

Comments
 (0)