2265. Count Nodes Equal to Average of Subtree
T: O(n)
S: O(n)
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
leaf node is ok
post order
*/
class Solution {
private int result = 0;
public int averageOfSubtree(TreeNode root) {
dfs(root);
return result;
}
private int[] dfs(TreeNode node) {
if (node == null) {
return new int[] {0, 0};
}
int[] left = dfs(node.left);
int[] right = dfs(node.right);
int currentSum = left[0] + right[0] + node.val;
int currentCount = left[1] + right[1] + 1;
if ((currentSum/currentCount) == node.val) {
result++;
}
return new int[] {currentSum, currentCount};
}
}
/***
T: O(n)
S: O(n)
*/
```
Last updated