題目描述:
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.舉例:
Given the below binary tree, 1 / 2 3 Return 6.
題目分析: 找從任意節點出發的任意路徑的最大長度。 每個node都有可能是其他路徑上的node,這種情況要max(left,right)。如此迴圈。 每個node都有可能作為中心node,此時要max(左側之前的路徑最長長度,左側之前的路徑最長長度,此node為中心時候的長度)
將這個分析單元遞迴封裝,即可實現目標。
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self,node):
ls = rs = None
lmv = rmv = 0
if node.left:
lmv,ls=self.dfs(node.left)
lmv=max(lmv,0)
if node.right:
rmv,rs=self.dfs(node.right)
rmv=max(rmv,0)
# print(lmv,rmv,ls,rs)
mv=node.val+max(lmv,rmv)
sv=node.val+lmv+rmv
# mv=node.val
trans_list=[elem for elem in [sv,ls,rs] if elem]
if not trans_list:
trans_list=[0]
return mv,max(trans_list)
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return
mv,smv=self.dfs(root)
return max(mv,smv)
if __name__==`__main__`:
tn=TreeNode(2)
tn1=TreeNode(-1)
tn2=TreeNode(-2)
tn.left=tn1
tn.right=tn2