124. Binary Tree Maximum Path Sum
dfs
Input:
[1,2,3]
1
/ \
2
3
Output:
6Input:
[-10,9,20,null,null,15,7]
-10
/ \
9
20
/ \
15 7
Output:
42Last updated
dfs
Input:
[1,2,3]
1
/ \
2
3
Output:
6Input:
[-10,9,20,null,null,15,7]
-10
/ \
9
20
/ \
15 7
Output:
42Last updated
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
ans = float("-inf")
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.dfs(root)
return self.ans
def dfs(self,root):
if not root:
return 0
left = max(0,self.dfs(root.left))
right = max(0,self.dfs(root.right))
self.ans = max(self.ans,left+right+root.val)
return max(0,left+root.val,right+root.val)