fromtypingimportOptionalclassTreeNode:
"""
Representsanodeinabinarytree.Attributes:val:Thevalueofthenode.left:Theleftchildnode.right:Therightchildnode.
"""
def__init__(self,val=0,left=None,right=None):self.val=valself.left=leftself.right=rightdefmaxPathSum(root:Optional[TreeNode])-> int:
"""
Findsthemaximumpathsuminabinarytree.Apathisdefinedasanysequenceofnodesfromsomestartingnodetoanynodeinthetreealongtheparent-childconnections.Thepathmustcontainatleastonenode.Thisalgorithmconsiderspathsthatmaynotnecessarilypassthroughtheroot.Args:root:Therootnodeofthebinarytree.Returns:Themaximumsumofapathinthetree.Returnsnegativeinfinityifthetreeisempty.
"""
ans=float('-inf')# Initialize the maximum path sum to negative infinity. This handles cases with all negative values.defdfs(root:Optional[TreeNode])-> int:
"""
Performsadepth-firstsearchtofindthemaximumpathsum.Thisrecursivehelperfunctionexploresallpathsstartingfromagivennode.Args:root:Thecurrentnodebeingvisited.Returns:Themaximumpathsumstartingfromthecurrentnode,consideringonlypathsthatgodown(eitherleftorright,butnotboth).Thisiscrucialforpreventingdouble-counting.
"""
nonlocalans# Access the 'ans' variable from the outer scope.ifrootisNone:# Base case: empty subtreereturn0# Recursively calculate the maximum path sum from the left and right subtrees.# We use max(dfs(root.left), 0) to handle negative path sums. If a subtree's max path sum is negative, we ignore it.left=max(dfs(root.left),0)right=max(dfs(root.right),0)# Update the maximum path sum found so far. This line considers paths that pass through the current node.ans=max(ans,root.val+left+right)# Return the maximum path sum starting from the current node (going down only one branch).returnroot.val+max(left,right)dfs(root)returnans
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2024-10-10。"],[],[]]