[NeetCode 150] Binary Tree Maximum Path Sum

Binary Tree Maximum Path Sum

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

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes has an edge connecting them. A node can not appear in the sequence more than once. The path does not necessarily need to include the root.

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

Example 1:

Input: root = [1,2,3]

Output: 6

Explanation: The path is 2 -> 1 -> 3 with a sum of 2 + 1 + 3 = 6.

Example 2:

Input: root = [-15,10,20,null,null,15,5,-5]

Output: 40

Explanation: The path is 15 -> 20 -> 5 with a sum of 15 + 20 + 5 = 40.

Constraints:

1 <= The number of nodes in the tree <= 1000.
-1000 <= Node.val <= 1000

Solution

It is an easy dp on the tree. For each node, there are four possible ways to get the maximum path:

  1. The node itself;
  2. The maximum path passing its left child plus itself;
  3. The maximum path passing its right child plus itself;
  4. The maximum path passing its left, right child plus itself.
    (p.s. If all the values of nodes are positive, there will only be the 4th case)

and in the process of DFS, we should return the maximum path passing itself, with three cases:

  1. The node itself
  2. The maximum path passing its left child plus itself;
  3. The maximum path passing its right child plus itself;
    (p.s. If all the values of nodes are positive, there will only be the 2nd & 3rd cases)

Code

# 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:
        ans = float('-inf')
        def dfs(node):
            nonlocal ans
            if node is None:
                return 0
            leftsum = dfs(node.left)
            rightsum = dfs(node.right)
            ans = max([ans, leftsum+rightsum+node.val, leftsum+node.val, rightsum+node.val, node.val])
            return max([leftsum+node.val, rightsum+node.val, node.val])
        dfs(root)

        return ans
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值