LeetCode 2265: Count Nodes Equal to Average of Subtree

Problem Description

Explanation:

To solve this problem, we can perform a depth-first search (DFS) on the binary tree. For each node, we will recursively calculate the sum and count of nodes in its subtree. With this information, we can determine the average of the subtree and compare it with the node's value. If they are equal, we increment a counter.

Algorithm:

  1. Implement a recursive function that calculates the sum and count of nodes in the subtree rooted at a given node.
  2. Perform a DFS on the binary tree and at each node:
    • Calculate the sum and count of nodes in its subtree.
    • Check if the node's value is equal to the average of the subtree.
    • Increment the counter if they are equal.
  3. Return the total count of nodes where the value is equal to the average of the subtree.

Time Complexity:

The time complexity of this approach is O(n), where n is the number of nodes in the binary tree. This is because we visit each node exactly once during the DFS traversal.

Space Complexity:

The space complexity is O(h), where h is the height of the binary tree. This is due to the recursive stack space used during the DFS traversal. :

Solutions

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    public int countEqualAverage(TreeNode root) {
        return dfs(root)[0];
    }
    
    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[1] + right[1] + node.val;
        int count = left[0] + right[0] + 1;
        
        int total = (node.val * count == sum) ? 1 : 0;
        
        return new int[]{total + left[0] + right[0], sum};
    }
}

Loading editor...