124. Binary Tree Maximum Path Sum
# 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 maxPathSum(self, root: Optional[TreeNode]) -> int:
self.res = -sys.maxsize
self.fromRoot(root)
return self.res
def fromRoot(self, root) -> int:
if not root:
return 0
left = self.fromRoot(root.left)
right = self.fromRoot(root.right)
pathSum = root.val
if left > 0:
pathSum += left
if right > 0:
pathSum += right
self.res = max(self.res, pathSum)
more = max(0, left, right)
return root.val + more