【二叉树-中等】1339. 分裂二叉树的最大乘积

【题目】
【代码】
【二叉树-中等】1339. 分裂二叉树的最大乘积_第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
class Solution:
    def dfs(self,root,s=0):
        if not root:return 0
        l=self.dfs(root.left)
        r=self.dfs(root.right)
        s+=l+r+root.val
        self.s.append(s)
        return s

    def maxProduct(self, root: Optional[TreeNode]) -> int:
        self.s=[]
        self.dfs(root)
        self.s.sort()
        max_num=self.s[-1]
        ans=1
        for i in range(len(self.s)):
            if self.s[i]>=max_num//2:
                if i-1>=0:
                    ans=max(ans,self.s[i-1]*(max_num-self.s[i-1]))
        return ans%(pow(10,9)+7)

【稍许改动】
【二叉树-中等】1339. 分裂二叉树的最大乘积_第2张图片

# 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 dfs(self,root,s=0):
        if not root:return 0
        l=self.dfs(root.left)
        r=self.dfs(root.right)
        s+=l+r+root.val
        self.s.append(s)
        return s

    def maxProduct(self, root: Optional[TreeNode]) -> int:
        self.s=[]
        self.dfs(root)
        self.s.sort()
        ans=1
        for i in range(len(self.s)):
            if self.s[i]>=self.s[-1]//2:
                if i-1>=0:
                    ans=max(ans,self.s[i-1]*(self.s[-1]-self.s[i-1]))
                if i+1<len(self.s):
                    ans=max(ans,self.s[i]*(self.s[-1]-self.s[i]))
                break
        return ans%(pow(10,9)+7)

你可能感兴趣的:(刷题,深度优先,leetcode,算法)