描述:递归调用,getMax返回 [节点值,经过节点左子节点的最大值,经过节点右节点的最大值],每次递归同时查看是否存在不经过节点的值大于max。
代码:待优化
1 def getLargeNode(self, a, b): 2 if a and b: 3 return max(a, b) 4 elif a and not b: 5 return a 6 elif not a and b: 7 return b 8 else: 9 tmp = None 10 11 def getMax(self, node): 12 if node is None: 13 return [None, None, None] 14 15 left = self.getMax(node.left) 16 right = self.getMax(node.right) 17 18 pass_node_max = node.val 19 if left[0] is not None: 20 if left[1] > self.maxPath: 21 self.maxPath = item 22 if left[2] > self.maxPath: 23 self.maxPath = item 24 25 tmp = self.getLargeNode(left[1], left[2]) 26 27 if tmp is not None: 28 if tmp <= 0 and left[0] <= 0: 29 left_val = left[0] 30 elif tmp > 0 and left[0] <= 0: 31 left_val = left[0] + tmp 32 if tmp + left[0] > 0: 33 pass_node_max += left_val 34 elif tmp <= 0 and left[0] > 0: 35 left_val = left[0] 36 pass_node_max += left_val 37 else: 38 left_val = left[0] + tmp 39 pass_node_max += left_val 40 else: 41 left_val = left[0] 42 if left[0] > 0: 43 pass_node_max += left[0] 44 else: 45 left_val = None 46 47 if right[0] is not None: 48 if right[1] > self.maxPath: 49 self.maxPath = right[1] 50 if right[2] > self.maxPath: 51 self.maxPath = right[1] 52 53 tmp = self.getLargeNode(right[1], right[2]) 54 55 if tmp is not None: 56 if tmp <= 0 and right[0] <= 0: 57 right_val = right[0] 58 elif tmp > 0 and right[0] <= 0: 59 right_val = right[0] + tmp 60 if tmp + right[0] > 0: 61 pass_node_max += right_val 62 elif tmp <= 0 and right[0] > 0: 63 right_val = right[0] 64 pass_node_max += right_val 65 else: 66 right_val = right[0] + tmp 67 pass_node_max += right_val 68 else: 69 right_val = right[0] 70 if right[0] > 0: 71 pass_node_max += right[0] 72 else: 73 right_val = None 74 75 if pass_node_max > self.maxPath: 76 self.maxPath = pass_node_max 77 78 return [node.val, left_val, right_val] 79 80 def maxPathSum(self, root): 81 self.maxPath = root.val 82 if not(root.left or root.right): 83 return self.maxPath 84 85 result = self.getMax(root) 86 87 root_val = root.val 88 if result[1] > 0: 89 root_val += result[1] 90 if result[2] > 0: 91 root_val += result[2] 92 if root_val > self.maxPath: 93 self.maxPath = root_val 94 95 if result[1] > self.maxPath: 96 self.maxPath = result[1] 97 if result[2] > self.maxPath: 98 self.maxPath = result[2] 99 100 return self.maxPath