给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
输出: 42
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.maxv = -1000000000
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
self.calc(root)
return self.maxv
def calc(self, root):
if root is None:
return 0
temp = root.val
lmax = self.calc(root.left)
rmax = self.calc(root.right)
if lmax > 0:
temp += lmax
if rmax > 0:
temp += rmax
if temp > self.maxv:
self.maxv = temp
return max(root.val, max(root.val + lmax, root.val + rmax))