给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.res = -10000
def get_max(self, root: TreeNode) -> int:
if not root:
return 0
left = self.get_max(root.left)
right = self.get_max(root.right)
x1 = root.val + max(left, 0) + max(right, 0)
x2 = root.val + max(0, max(left, right))
self.res = max(self.res, max(x1, x2))
return x2
def maxPathSum(self, root: TreeNode) -> int:
self.get_max(root)
return self.res