leetcode1343
Posted AsenYang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1343相关的知识,希望对你有一定的参考价值。
1 class Solution: 2 def __init__(self): 3 self.subTrees = [] 4 self.sums = 0 5 self.memo = {} 6 def preOrder(self,root): 7 if root != None: 8 self.sums += root.val 9 self.subTrees.append(self.subTreeSum(root)) 10 self.preOrder(root.left) 11 self.preOrder(root.right) 12 13 def subTreeSum(self,root): 14 if root.left == None and root.right == None: 15 self.memo[root] = root.val 16 return root.val 17 elif root.left != None and root.right != None: 18 cur,left,right = 0,0,0 19 if root in self.memo: 20 return self.memo[root] 21 else: 22 cur = root.val 23 if root.left in self.memo: 24 left = self.memo[root.left] 25 else: 26 left = self.subTreeSum(root.left) 27 if root.right in self.memo: 28 right = self.memo[root.right] 29 else: 30 right = self.subTreeSum(root.right) 31 self.memo[root] = cur + left + right 32 return cur + left + right 33 elif root.left != None: 34 cur,left,right = 0,0,0 35 if root in self.memo: 36 return self.memo[root] 37 else: 38 cur = root.val 39 if root.left in self.memo: 40 left = self.memo[root.left] 41 else: 42 left = self.subTreeSum(root.left) 43 self.memo[root] = cur + left + right 44 return cur + left 45 elif root.right != None: 46 cur,left,right = 0,0,0 47 if root in self.memo: 48 return self.memo[root] 49 else: 50 cur = root.val 51 if root.right in self.memo: 52 right = self.memo[root.right] 53 else: 54 right = self.subTreeSum(root.right) 55 self.memo[root] = cur + left + right 56 return cur + right 57 58 def maxProduct(self, root: ‘TreeNode‘) -> int: 59 self.preOrder(root) 60 #print(self.sums) 61 #print(self.subTrees) 62 result = 0 63 for i in range(len(self.subTrees)): 64 part1 = self.subTrees[i] 65 part2 = self.sums - part1 66 product = part1 * part2 67 result = max(result,product) 68 return result % (1000000007)
算法思路:二叉树遍历+memo缓存。
遍历二叉树(本题使用先序遍历),同时计算每一棵子树的所有节点的和。使用缓存记录已经计算过的子树和,以加快算法的执行效率。
得到所有子树的和之后,用树所有节点的和减去任意一个子树的和,将原二叉树分为两部分。
计算这两部分的乘积,保留乘积的最大值。最终结果对1000000007取余,即为所求。
以上是关于leetcode1343的主要内容,如果未能解决你的问题,请参考以下文章
leetcode1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
RGB检测基于matlab GUI图像RGB检测含Matlab源码 1343期