-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree_maximum_path_sum.py
30 lines (22 loc) · 1.23 KB
/
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
'''
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
'''
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.max_sum = float('-inf')
self.dfs(root)
return self.max_sum
def dfs(self, node):
if not node: return 0
# only add positive contributions
leftST_sum = max(0, self.dfs(node.left))
rightST_sum = max(0, self.dfs(node.right))
# check if cumulative sum at current node > global max sum so far
# this evaluates a candidate path
self.max_sum = max(self.max_sum, leftST_sum + rightST_sum + node.val)
# add to the current node ONLY one of the children contributions
# in order to maintain the constraint of considering only paths
# if not, we would be exploring explore the whole tree - against problem definition
return max(leftST_sum, rightST_sum) + node.val