1. # Definition for a binary tree node.
    2. # class TreeNode:
    3. # def __init__(self, val=0, left=None, right=None):
    4. # self.val = val
    5. # self.left = left
    6. # self.right = right
    7. class Solution:
    8. def maxPathSum(self, root: TreeNode) -> int:
    9. return self.maxPathhelper(root)[1]
    10. def maxPathhelper(self, root):
    11. if root == None:
    12. return 0, float('-inf')
    13. left = self.maxPathhelper(root.left)
    14. right = self.maxPathhelper(root.right)
    15. singlePath = max(left[0], right[0]) + root.val
    16. singlePath = max(singlePath, 0) #important line!!!
    17. maxPath = max(left[1], right[1], left[0] + right[0] + root.val)
    18. return singlePath, maxPath