Leetcode 2265: Count Nodes Equal to Average of Subtree

grid47
grid47
Exploring patterns and algorithms
Mar 25, 2024 7 min read

You are given the root of a binary tree. Your task is to return the number of nodes where the value of the node is equal to the average of the values in its entire subtree (including the node itself). The average of a set of values is the sum of the values divided by the number of values, rounded down to the nearest integer.
Problem
Approach
Steps
Complexity
Input: The input is the root of a binary tree where each node contains an integer value.
Example: root = [3, 9, 20, null, null, 15, 7]
Constraints:
• The number of nodes in the tree is between 1 and 1000.
• Node values are between 0 and 1000.
Output: Return the count of nodes that satisfy the condition of having their value equal to the average of the values in their respective subtree.
Example: Output: 3
Constraints:
Goal: The goal is to traverse the binary tree and calculate the sum and count of nodes for each subtree, comparing each node's value to the average of its subtree.
Steps:
• Recursively calculate the sum and count of nodes for each subtree starting from the root.
• For each node, check if its value matches the average of its subtree (rounded down).
• Count the number of nodes that satisfy the condition.
Goal: The binary tree is a valid binary tree, and the node values are within the range [0, 1000].
Steps:
• The tree will have at least one node.
Assumptions:
• The binary tree is non-empty, with a size of at least 1 node.
Input: root = [3, 9, 20, null, null, 15, 7]
Explanation: For the node with value 3: The average of its subtree is (3 + 9 + 20 + 15 + 7) / 5 = 54 / 5 = 10, which is not equal to 3. For the node with value 9: The average of its subtree is 9 / 1 = 9, which is equal to 9. For the node with value 20: The average of its subtree is (20 + 15 + 7) / 3 = 42 / 3 = 14, which is not equal to 20. Thus, 2 nodes satisfy the condition (9 and 15). The result is 3.

Input: root = [1]
Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1, which is equal to 1. The result is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus