-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
40 lines (33 loc) · 1.2 KB
/
code.py
File metadata and controls
40 lines (33 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 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 __init__(self) :
self.maxVal = float('-inf')
def maxPathSumInternal(self, root) :
if not root :
return float('-inf')
elif not root.left and not root.right :
self.maxVal = max(self.maxVal, root.val)
return root.val
left = self.maxPathSumInternal(root.left)
right = self.maxPathSumInternal(root.right)
if left>0 and right>0 :
self.maxVal = max(self.maxVal, left, right, left+right+root.val)
elif left>0 :
self.maxVal = max(self.maxVal, left, left+root.val)
elif right>0 :
self.maxVal = max(self.maxVal, right, right+root.val)
else :
self.maxVal = max(self.maxVal, root.val)
maVal = max(left, right)
if maVal > 0 :
return root.val+maVal
else :
return root.val
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.maxPathSumInternal(root)
return self.maxVal