forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8804who.py
More file actions
31 lines (24 loc) · 909 Bytes
/
8804who.py
File metadata and controls
31 lines (24 loc) · 909 Bytes
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
# 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.answer = -1e9
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.getSum(root, 0)
return self.answer
def getSum(self, node, depth):
val = node.val
leftMax = self.getSum(node.left, depth+1) if node.left else 0
rightMax = self.getSum(node.right, depth+1) if node.right else 0
temp = val + (leftMax if leftMax > 0 else 0) + (rightMax if rightMax > 0 else 0)
if self.answer < temp:
self.answer = temp
if leftMax > rightMax:
val += leftMax if leftMax > 0 else 0
else:
val += rightMax if rightMax > 0 else 0
return val