MediumNo. 2265

Count Nodes Equal to Average of Subtree — LeetCode 2265 Python Solution

Topics
Tree, Depth-First Search, Binary Tree
Reading time
3 min

The problem

Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. Note: The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.

Example

Input
root = [4,8,5,0,1,null,6]
Output
5
Explanation
For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.

Python solution

PythonSolution
class Solution:
    def averageOfSubtree(self, root: TreeNode) -> int:
        def dfs(root) -> tuple:
            if not root:
                return 0, 0
            ls, ln = dfs(root.left)
            rs, rn = dfs(root.right)
            s = ls + rs + root.val
            n = ln + rn + 1
            nonlocal ans
            ans += int(s // n == root.val)
            return s, n

        ans = 0
        dfs(root)
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2265. Count Nodes Equal to Average of Subtree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0098Validate Binary Search TreeMedium
0099Recover Binary Search TreeMedium
0100Same TreeEasy
0101Symmetric TreeEasy
0104Maximum Depth of Binary TreeEasy
0110Balanced Binary TreeEasy

Frequently asked questions

How hard is LeetCode 2265. Count Nodes Equal to Average of Subtree?

LeetCode 2265. Count Nodes Equal to Average of Subtree is rated Medium on LeetCode.

What is the time complexity of LeetCode 2265. Count Nodes Equal to Average of Subtree?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 2265. Count Nodes Equal to Average of Subtree?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2265. Count Nodes Equal to Average of Subtree cover?

LeetCode 2265. Count Nodes Equal to Average of Subtree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.