Skip to content

2265. Count Nodes Equal to Average of Subtree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int averageOfSubtree(TreeNode* root) {
    int ans = 0;
    dfs(root, ans);
    return ans;
  }

 private:
  pair<int, int> dfs(TreeNode* root, int& ans) {
    if (root == nullptr)
      return {0, 0};
    const auto [leftSum, leftCount] = dfs(root->left, ans);
    const auto [rightSum, rightCount] = dfs(root->right, ans);
    const int sum = root->val + leftSum + rightSum;
    const int count = 1 + leftCount + rightCount;
    if (sum / count == root->val)
      ++ans;
    return {sum, count};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int averageOfSubtree(TreeNode root) {
    dfs(root);
    return ans;
  }

  private int ans = 0;

  private Pair<Integer, Integer> dfs(TreeNode root) {
    if (root == null)
      return new Pair<>(0, 0);
    Pair<Integer, Integer> left = dfs(root.left);
    Pair<Integer, Integer> right = dfs(root.right);
    final int sum = root.val + left.getKey() + right.getKey();
    final int count = 1 + left.getValue() + right.getValue();
    if (sum / count == root.val)
      ++ans;
    return new Pair<>(sum, count);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def averageOfSubtree(self, root: TreeNode | None) -> int:
    ans = 0

    def dfs(root: TreeNode | None) -> tuple[int, int]:
      nonlocal ans
      if not root:
        return (0, 0)
      leftSum, leftCount = dfs(root.left)
      rightSum, rightCount = dfs(root.right)
      summ = root.val + leftSum + rightSum
      count = 1 + leftCount + rightCount
      if summ // count == root.val:
        ans += 1
      return (summ, count)

    dfs(root)
    return ans