2265. Count Nodes Equal to Average of Subtree

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
class Solution {
public int averageOfSubtree(TreeNode root) {
return dfs(root)[2];
}

private int[] dfs(TreeNode root) {
int[] res = new int[3]; // (subNodeSum, subNodeCount, averageNodeCount)

if (root == null) {
return res;
}

int[] left = dfs(root.left);
int[] right = dfs(root.right);

int nodeSum = left[0] + right[0] + root.val;
int nodeCount = left[1] + right[1] + 1;
if (nodeSum / nodeCount == root.val) {
res[2] += 1;
}
res[0] = nodeSum;
res[1] = nodeCount;
res[2] += left[2] + right[2];

return res;
}
}

注意节点平均值的计算题目要求直接使用除法,除不尽的部分直接丢弃。

References

2265. Count Nodes Equal to Average of Subtree