Leetcode | 124. Binary Tree Maximum Path Sumツリーの最大パスと

1681 ワード

https://leetcode.com/problems/binary-tree-maximum-path-sum/
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

問題を解く構想:要求するのは実は“1つの筆画”が通ることができる経路の中で、数値と最大のあれです.では、各ノードについて、頂点としての最大とパスを求め、ポイントごとにupdateで最大値を求めることができます.
下の図に示すように(ノードの数字は符号で、値ではありません)、6、7番のノードが負の場合、オレンジ色の線は2を頂点とする可能性のある最大パスです.最大パスはリーフノードを起止ノードとする必要もなく、ルートノードを通過する必要もないことにも留意されたい.
 
# 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
        """
        self.max = float('-inf')
        self.helper(root)
        return self.max
    
    def helper(self,root):
        if not root:
            return 0
        left = max(0, self.helper(root.left)) #       0,        ,     
        right = max(0, self.helper(root.right))
        
        self.max = max(self.max, root.val+left+right) #         root  “  ”      
        return root.val + max(left,right)  #   “  ”  ,           root       。(       left/right,        )