Skip to content

Commit 80d8092

Browse files
committed
Binary Tree Maximum Path Sum
1 parent 2fbd0da commit 80d8092

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Given a binary tree, find the maximum path sum.
3+
4+
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
5+
6+
For example:
7+
Given the below binary tree,
8+
9+
1
10+
/ \
11+
2 3
12+
Return 6.
13+
'''
14+
15+
# Definition for a binary tree node.
16+
class TreeNode(object):
17+
def __init__(self, x):
18+
self.val = x
19+
self.left = None
20+
self.right = None
21+
22+
23+
class Solution(object):
24+
def maxPathSum(self, root):
25+
"""
26+
:type root: TreeNode
27+
:rtype: int
28+
"""
29+
self.maxSum = float('-inf')
30+
self._maxPathSum(root)
31+
return self.maxSum
32+
33+
def _maxPathSum(self, root):
34+
if root is None:
35+
return 0
36+
left = self._maxPathSum(root.left)
37+
right = self._maxPathSum(root.right)
38+
left = left if left > 0 else 0
39+
right = right if right > 0 else 0
40+
self.maxSum = max(self.maxSum, root.val + left + right)
41+
return max(left, right) + root.val

0 commit comments

Comments
 (0)