1
/ \
2   3

-10
/ \
9  20
/  \
15   7

# 三、代码

# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return str(self.val)

class Solution:
def maxPathSum(self, root: TreeNode) -> int:

self.result = root.val
def dfs(root):
if not root:
return 0
left = max(dfs(root.left), 0)  # less than 0, no pass
right = max(dfs(root.right), 0)  # less than 0, no pass

self.result = max(root.val + left + right, self.result)
return root.val + max(left, right)  # choose left or right
dfs(root)
return self.result

if __name__ == '__main__':
# a = TreeNode(-10)
# a.left = TreeNode(9)
# a.right = TreeNode(20)
# a.right.left = TreeNode(15)
# a.right.right = TreeNode(7)
a = TreeNode(1)
a.left = TreeNode(-2)
a.right = TreeNode(3)

s = Solution()
ans = s.maxPathSum(a)
print(ans)

07-25 1353
05-31 2945

09-24 352
06-11 479
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。