-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path124.py
26 lines (23 loc) · 844 Bytes
/
124.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
# https://neetcode.io/problems/binary-tree-maximum-path-sum
# https://leetcode.com/problems/binary-tree-maximum-path-sum/description/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from typing import Optional
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
maxSum = float('-inf')
def dfs(root):
if not root:
return 0
nonlocal maxSum
lSum = dfs(root.left)
rSum = dfs(root.right)
greaterPath = max(lSum + root.val, rSum + root.val, root.val)
maxSum = max(maxSum, greaterPath, greaterPath + min(lSum, rSum))
return greaterPath
dfs(root)
return maxSum