-
Notifications
You must be signed in to change notification settings - Fork 0
/
1339. Maximum Product of Splitted Binary Tree.py
90 lines (61 loc) · 2.09 KB
/
1339. Maximum Product of Splitted Binary Tree.py
1
# 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 = rightclass Solution: def maxProduct(self, root: TreeNode) -> int: """ total = 0 def get_sum(node): nonlocal total if not node: return total += node.val get_sum(node.left) get_sum(node.right) get_sum(root) def postorder(node): if not node: return 0 left = postorder(node.left) right = postorder(node.right) return node.val + left + right def dfs(node): nonlocal res if not node: return if not node.left and not node.right: res = max(res, node.val * (total-node.val)) return sub = postorder(node) res = max(res, sub * (total-sub)) dfs(node.left) dfs(node.right) res = 0 dfs(root) return res % (10**9+7) """ dic = collections.defaultdict(int) def get_sum(node): nonlocal dic if not node: return 0 left = get_sum(node.left) right = get_sum(node.right) dic[node] = node.val + left + right return node.val + left + right get_sum(root) total = dic[root] res = 0 def dfs(node): nonlocal res if not node: return res = max(res, dic[node] * (total-dic[node])) dfs(node.left) dfs(node.right) dfs(root.left) dfs(root.right) return res % (10**9+7)