LeetCode 124. Binary Tree Maximum Path Sum
原题
求二叉树的最大路径和
Given a 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.
For example:
Given the below binary tree,1 / \ 2 3
Return
6.
解题思路
- 可以采用一步步加深难度的解题思路,先考虑二叉树节点值全部为正的情况下的解法,再考虑存在负值时的情况,这样更容易解出答案
- 本题可以采用递归求解
- 难点在于递归返回的最大路径和和我们要求的最大路径和是不同的,返回值必须是单路的,而最大路径可以是左右子树相加的
- 所以我们可以设置一个全局变量来保存我们要求的最大路径和,在递归中不断刷新最大路径和
代码实现
# 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.maxPath = -sys.maxint
self.helper(root)
return self.maxPath
def helper(self, node):
if node == None:
return 0
lMax = self.helper(node.left)
rMax = self.helper(node.right)
# 局部最大路径 = 根节点值 + 左、右最大路径(必须为正才能加)
MaxSum = node.val
if lMax > 0:
MaxSum += lMax
if rMax > 0:
MaxSum += rMax
self.maxPath = max(self.maxPath, MaxSum)
# 返回值为单一路径最大值,如果左、右最大路径均为负,则返回根节点值
return max(lMax, rMax, 0) + node.val

浙公网安备 33010602011771号