9 lines O(n) Python

  • 1

    Updating node.val by the bigger one between left and right, and ignore them when none of them is positive.

    class Solution(object):
        def maxPathSum(self, root):
            :type root: TreeNode
            :rtype: int
            def path(node):
                if not node: return 0
                left, right = max(path(node.left), 0), max(path(node.right), 0)
                self.ans = max(self.ans, left + right + node.val)
                node.val += max(left, right)
                return node.val
            self.ans = float('-inf')
            return self.ans if root else 0

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.