-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree_max_sum_path.py
More file actions
49 lines (37 loc) · 1.01 KB
/
Copy pathtree_max_sum_path.py
File metadata and controls
49 lines (37 loc) · 1.01 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
41
42
43
44
45
46
47
48
49
import sys
# https://leetcode.com/problems/binary-tree-maximum-path-sum/
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.maxSum = -sys.maxsize
self.calculatePathSum(root)
return self.maxSum
def calculatePathSum(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
if root.val > self.maxSum:
self.maxSum = root.val
return root.val
leftPathSum = self.calculatePathSum(root.left)
rightPathSum = self.calculatePathSum(root.right)
sum = root.val
if leftPathSum > 0:
sum += leftPathSum
if rightPathSum > 0:
sum += rightPathSum
self.maxSum = max(self.maxSum, sum)
return max(root.val, root.val + max(leftPathSum, rightPathSum))
def main():
str = input('input: ')
output = function(str)
print('output: ', output)
if __name__ == '__main__':
main()