Binary Tree Maximum Path Sum
Question
What is the maximum possible sum of values from a root node to any leaf node in a binary tree?
Example 1
Input: [-10,9,20,null,null,15,7]
Output: 42
Solution
- ▭
- ▯
all//Binary Tree Maximum Path Sum.py
# 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):
        self.ans = float('-inf')
        def util(node):
            if not node:
                return 0
            left = max(util(node.left), 0)
            right = max(util(node.right), 0)
            self.ans = max(self.ans, node.val + left + right)
            return max(left, right) + node.val
        util(root)
        return self.ans
all//Binary Tree Maximum Path Sum.py
# 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):
        self.ans = float('-inf')
        def util(node):
            if not node:
                return 0
            left = max(util(node.left), 0)
            right = max(util(node.right), 0)
            self.ans = max(self.ans, node.val + left + right)
            return max(left, right) + node.val
        util(root)
        return self.ans