Back to September Back to Year 2026
MEDIUM 10 Sep 2026 View on LeetCode

2265. Count Nodes Equal to Average of Subtree

</> Solution

/**
 * Problem: LeetCode 2265 - Count Nodes Equal to Average of Subtree
 * Difficulty: Medium
 * Language: Java
 * Author: CodeByTushu
 */
/**
 * 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;
 *     }
 * }
 */
/**
 * Problem: LeetCode 2265 - Count Nodes Equal to Average of Subtree
 * Difficulty: Medium
 * Language: Java
 * Author: CodeByTushu
 */
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 Depth-First Search Tree