Binary Tree Maximum Path Sum

PHOTO EMBED

Sun Mar 17 2024 20:05:10 GMT+0000 (Coordinated Universal Time)

Saved by @playadust

class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        res = [root.val]

        # return max path sum without split
        def dfs(root):
            if not root:
                return 0

            leftMax = dfs(root.left)
            rightMax = dfs(root.right)
            leftMax = max(leftMax, 0)
            rightMax = max(rightMax, 0)

            # compute max path sum WITH split
            res[0] = max(res[0], root.val + leftMax + rightMax)
            return root.val + max(leftMax, rightMax)

        dfs(root)
        return res[0]
content_copyCOPY

https://leetcode.com/problems/binary-tree-maximum-path-sum/

https://www.youtube.com/watch?v=Hr5cWUld4vU