Image credit: Academic

124. Binary Tree Maximum Path Sum

題目來自Leetcode

題目

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

   1
  / \
 2   3

Output: 6 Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

bottom-up遞迴想法

path sum的延伸,每條路徑只能走過一次,那麼一個node的最大和肯定為其左右子樹的最大加上本身node.val,左邊路徑的最大和為左節點值加上其左右路徑最大和,右邊路徑亦然 tricky part:若有負的情況,為了不讓node被負數拖累,每次得到左右子樹最大值時,先讓他們跟0比較,這樣就可以去掉負數的影響,保留node的值

Code

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def helper(root):
            if not root:
                return 0
            # 若遇到負數,需要過濾下面的答案,才不會讓root.val越加越小
            L = max(0, helper(root.left))
            R = max(0, helper(root.right))
            
            Sum = root.val + L + R
            self.Max = max(self.Max, Sum)
            return root.val + max(L, R) # return local maximum + root
        
        if not root: return 0
        self.Max = float("-inf")
        helper(root)
        return self.Max

Related

comments powered by Disqus