Skip to content

Commit 2478fc7

Browse files
authored
Create 124-Binary-Tree-Maximum-Path-Sum.py
1 parent f93906b commit 2478fc7

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

124-Binary-Tree-Maximum-Path-Sum.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def maxPathSum(self, root: TreeNode) -> int:
9+
res = [root.val]
10+
11+
# return max path sum without split
12+
def dfs(root):
13+
if not root:
14+
return 0
15+
16+
leftMax = dfs(root.left)
17+
rightMax = dfs(root.right)
18+
leftMax = max(leftMax, 0)
19+
rightMax = max(rightMax, 0)
20+
21+
# compute max path sum WITH split
22+
res[0] = max(res[0], root.val + leftMax + rightMax)
23+
return root.val + max(leftMax, rightMax)
24+
25+
dfs(root)
26+
return res[0]

0 commit comments

Comments
 (0)