Skip to content

124. Binary Tree Maximum Path Sum

题目

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node's values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

 

Example 1:

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2:

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 104].
  • -1000 <= Node.val <= 1000
Related Topics
  • 深度优先搜索
  • 动态规划
  • 二叉树

  • 👍 2426
  • 👎 0
  • 思路

    本题的思路是递归的返回值和更新结果的值不同

    • 递归的返回值:
      • 当前节点 + 最大的一颗子树路径
    • 更新结果的值:
      • 当前节点 + 非负所有子树

    解法

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    
    
    class Solution:
        def maxPathSum(self, root: Optional[TreeNode]) -> int:
            self.res = -1001
    
            def dsf(root: Optional[TreeNode]) -> int:
                if not root:
                    return 0
    
                left = max(0, dsf(root.left))
                right = max(0, dsf(root.right))
    
    
                self.res = max(self.res, left + right + root.val)
    
                return root.val + max(left, right)
    
            dsf(root)
    
            return self.res
    
    
    
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度 O(N)
    • 空间复杂度 O(N)