124. 二叉树中的最大路径和

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

1
/
2 3

输出: 6
示例 2:

输入: [-10,9,20,null,null,15,7]

  -10
   /
  9  20
    /  
   15   7

输出: 42

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum

递归水题

# 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: TreeNode) -> int:
        def seek(node):
            if not node:
                return 0
            l=seek(node.left)
            r=seek(node.right)
            self.ans=max(self.ans,max(l,0)+max(r,0)+node.val)
            return max(l,r,0)+node.val
        seek(root)
        return self.ans
原文地址:https://www.cnblogs.com/xxxsans/p/13386588.html