-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmaxPathSum.py
34 lines (27 loc) · 1.19 KB
/
maxPathSum.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
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class NodeSumInfo:
def __init__(self, maxBranchSum, runningPathSum):
self.maxBranchSum = maxBranchSum
self.runningPathSum = runningPathSum
def maxPathSum(tree):
result = maxPathSumHelper(tree)
return result.runningPathSum
def maxPathSumHelper(tree):
if tree is None:
return NodeSumInfo(0, float("-inf"))
leftReturnCall = maxPathSumHelper(tree.left)
rightReturnCall = maxPathSumHelper(tree.right)
leftMaxSumAsBranch, leftMaxPathSum = leftReturnCall.maxBranchSum, leftReturnCall.runningPathSum
rightMaxSumAsBranch, rightMaxPathSum = rightReturnCall.maxBranchSum, rightReturnCall.runningPathSum
maxChildSumAsBranch = max(leftMaxSumAsBranch, rightMaxSumAsBranch)
value = tree.value
maxSumAsBranch = max(maxChildSumAsBranch+value, value)
maxSumAsTreeSum = max(leftMaxSumAsBranch+value +
rightMaxSumAsBranch, maxSumAsBranch)
maxPathSum = max(leftMaxPathSum,
rightMaxPathSum, maxSumAsTreeSum)
return NodeSumInfo(maxSumAsBranch, maxPathSum)