1. 程式人生 > >LeetCode 124. Binary Tree Maximum Path Sum(樹中最長路徑和,遞迴)

LeetCode 124. 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

解法
遞迴思路:
求某個節點的最長路徑和,只需要求左節點的最長路徑和left,右節點的最長路徑和right,以及當前節點的值val
maxpath = max(val, val+left, val+right, val+left+right)
遞迴函式返回的時候是一條鏈,因此返回max(val, val+left, val+right)

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

class Solution:
    def solve(self, root):
        if root:
            left = self.solve(root.left)
            right = self.solve(root.
right) val = root.val ret = max(val, val+left, val+right) self.ans = max(self.ans, ret, val+left+right) return ret return 0 def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ self.ans = -(1<<30) self.solve(root) return self.ans