엔지니어 게시판
LeetCode 솔루션 분류

[12/10] 1339. Maximum Product of Splitted Binary Tree

컨텐츠 정보

본문

1339. Maximum Product of Splitted Binary Tree 

Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.

Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.

Note that you need to maximize the answer before taking the mod and not after taking it.

 

Example 1:

Input: root = [1,2,3,4,5,6]
Output: 110
Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)

Example 2:

Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)

 

Constraints:

  • The number of nodes in the tree is in the range [2, 5 * 104].
  • 1 <= Node.val <= 104
Accepted
105.7K
Submissions
220.6K
Acceptance Rate
47.9%


관련자료

댓글 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 = right
from collections import deque
class Solution:
    def maxProduct(self, root: Optional[TreeNode]) -> int:
        MOD = 10**9+7

        queue = deque([root])
        allsum = 0
        while queue:
            node = queue.popleft()
            allsum += node.val
            if node.left: queue.append(node.left)
            if node.right: queue.append(node.right)

        max_mult = 0

        def dfs(node):
            if not node: return 0
            nonlocal max_mult
            left = dfs(node.left)
            right = dfs(node.right)
            sub_tree_sum = left+right+node.val
            max_mult = max(max_mult, (allsum - sub_tree_sum)*sub_tree_sum)

            return sub_tree_sum
        
        dfs(root)

        return max_mult%MOD


전체 405 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 516 명
  • 오늘 방문자 3,607 명
  • 어제 방문자 7,102 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,547 명
알림 0