Back to Month
MEDIUM 10 Sep 2026 View on LeetCode

2265. Count Nodes Equal to Average of Subtree

</> Solution

class Solution {
    int count = 0;
    public int averageOfSubtree(TreeNode root) {
        dfs(root);
        return count;
    }
    private int[] dfs(TreeNode node) {
        if (node == null) return new int[]{0, 0};
        int[] left  = dfs(node.left);
        int[] right = dfs(node.right);
        int sum      = left[0] + right[0] + node.val;
        int nodeCount = left[1] + right[1] + 1;
        int avg = sum / nodeCount;
        if (avg == node.val) count++;
        return new int[]{sum, nodeCount};
    }
}

TIME COMPLEXITY

O(n)

SPACE COMPLEXITY

O(h)

TOPICS

Binary Tree DFS Recursion Tree