标签:path sum any obj problem 左右 相加 最大值 答案 bsp
求二叉树的最大路径和
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
LeetCode 124. Binary Tree Maximum Path Sum
标签:path sum any obj problem 左右 相加 最大值 答案 bsp
原文地址:http://www.cnblogs.com/LiCheng-/p/6892562.html