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"]],["最終更新日 2024-10-10 UTC。"],[],[]]