-
Notifications
You must be signed in to change notification settings - Fork 0
/
124-Binary_Tree_Maximum_Path_Sum.py
55 lines (35 loc) · 1.41 KB
/
124-Binary_Tree_Maximum_Path_Sum.py
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
50
51
52
53
54
55
# 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
# Time: O(N)
# Space: O(H), H = tree High, to keep recursive stack
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
max_sum = float('-inf')
def max_gain(node):
nonlocal max_sum
if not node:
return 0
left_gain = max(max_gain(node.left), 0)
right_gain = max(max_gain(node.right), 0)
price_cur = node.val + left_gain + right_gain
max_sum = max( max_sum, price_cur )
return node.val + max( left_gain, right_gain )
max_gain(root)
return max_sum
class SolutionII:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
max_sum = root.val
def dfs( node ):
nonlocal max_sum
if not node:
return 0
l = dfs( node.left )
r = dfs( node.right )
max_sum = max( max_sum, node.val, node.val+l+r, node.val+l, node.val+r )
return max( node.val, node.val+l, node.val+r )
dfs(root)
return max_sum