# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
a.left = b
a.right = c
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
# 定义一个数字存放最大的路径和
self.max_sum = float("-inf")
def dfs(root):
# 当节点为空的时候返回零
if not root:return 0
# 递归左子树和右子树,并接收返回值
left = dfs(root.left)
right = dfs(root.right)
# self.max_sum必然是left或者right的子树的路径,
# 因此这里判断是否需要经过根节点
self.max_sum = max(self.max_sum,left + right + root.val)
# 这里不针对根节点,对于根节点的儿子节点来说,
# 路径只能包含儿子节点中的一个
return max(0,max(left,right) + root.val)
dfs(root)
return self.max_sum
A = Solution()
print(A.maxPathSum(a))