-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path124_binary_tree_maximum_path_sum.py
More file actions
60 lines (46 loc) · 1.34 KB
/
124_binary_tree_maximum_path_sum.py
File metadata and controls
60 lines (46 loc) · 1.34 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
50
51
52
53
54
55
56
57
58
59
60
"""
Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Solution:
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
ans, _ = self.divide_conquer(root)
return ans
def divide_conquer(self, node):
if not node:
return float('-inf'), 0
max_left, left = self.divide_conquer(node.left)
max_right, right = self.divide_conquer(node.right)
# 0 means discard the negative path
res = max(max_left, max_right, node.val + left + right)
path = max(node.val + left, node.val + right, 0)
return res, path
class Solution:
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.ans = float('-inf')
self.divide_conquer(root)
return self.ans
def divide_conquer(self, node):
if not node:
return 0
left = max(0, self.divide_conquer(node.left))
right = max(0, self.divide_conquer(node.right))
if node.val + left + right > self.ans:
self.ans = node.val + left + right
return node.val + max(left, right)