-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMax Path Sum In Binary Tree.py
More file actions
44 lines (32 loc) · 1.34 KB
/
Max Path Sum In Binary Tree.py
File metadata and controls
44 lines (32 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
"""
Max Path Sum In Binary Tree ♡
Write a function that takes in a Binary Tree and returns its max path sum.
A path is a collection of connected nodes in a tree, where no node is connected to more than two other
nodes; a path sum is the sum of the values of the nodes in a particular path.
Each BinaryTree node has an integer value , a left child node, and a right child node. Children
nodes can either be BinaryTree nodes themselves or None / null .
Sample Input
tree = 1
/ \
2 3
/ \ / \
4 5 6 7
Sample Output
18 // 5 + 2 + 1 + 3 + 7
"""
# SOLUTION 1
# O(n) time | O(log(n)) space
def maxPathSum(tree):
_, maxSum = findMaxSum(tree)
return maxSum
def findMaxSum(tree):
if tree is None:
return 0, float("-inf")
leftMaxSumAsBranch, leftMaxPathSum = findMaxSum(tree.left)
rightMaxSumAsBranch, rightMaxPathSum = findMaxSum(tree.right)
maxChildSumAsBranch = max(leftMaxSumAsBranch, rightMaxSumAsBranch)
value = tree.value
maxSumAsBranch = max(maxChildSumAsBranch + value, value)
maxSumAsRootNode = max(leftMaxSumAsBranch + value + rightMaxSumAsBranch, maxSumAsBranch)
maxPathSum = max(leftMaxPathSum, rightMaxPathSum, maxSumAsRootNode)
return maxSumAsBranch, maxPathSum