2265. Count Nodes Equal to Average of Subtree

Обновлено: 2024-03-12
1 мин
[]

Содержание

LeetCode problem 2265

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
        def dfs(root):
            if root is None:
                return 0, 0
            ls, ln = dfs(root.left)
            rs, rn = dfs(root.right)
            s = ls + rs + root.val
            n = ln + rn + 1
            if s // n == root.val:
                nonlocal res
                res += 1
            return s, n

        res = 0
        dfs(root)
        return res