Binary Tree Maximum Path Sum LeetCode solution in Python

1
class Solution:
2
def maxPathSum(self, root: Optional[TreeNode]) -> int:
3
self.res = root.val
4

5
def solving(root):
6
if not root:
7
return 0
8
current = root.val
9
sleft, sright = float("-inf"), float("-inf")
10
if root.left:
11
sleft = solving(root.left)
12
if sleft >= 0:
13
current += sleft
14
if root.right:
15
sright = solving(root.right)
16
if sright >= 0:
17
current += sright
18
if current > self.res:
19
self.res = current
20
return max(root.val, root.val + sleft, root.val + sright)
21

22
solving(root)
23
return self.res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0