Dashboard Temp Share Shortlinks Frames API

HTMLify

maximum-product-of-splitted-binary-tree.py
Views: 7 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def maxProduct(self, root: Optional[TreeNode]) -> int:
        subtree_sums = []
        
        def calculate_sum(node):
            if not node:
                return 0
            curr_sum = node.val + calculate_sum(node.left) + calculate_sum(node.right)
            subtree_sums.append(curr_sum)
            return curr_sum
        
        total_sum = calculate_sum(root)
        
        max_prod = 0
        for s in subtree_sums:
            prod = s * (total_sum - s)
            if prod > max_prod:
                max_prod = prod
                
        return max_prod % (10**9 + 7)