fromtypingimportOptionalclassTreeNode:""" Represents a node in a binary tree. Attributes: val: The value of the node. left: The left child node. right: The right child node. """def__init__(self,val=0,left=None,right=None):self.val=valself.left=leftself.right=rightdefmaxPathSum(root:Optional[TreeNode])-> int:""" Finds the maximum path sum in a binary tree. 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. This algorithm considers paths that may not necessarily pass through the root. Args: root: The root node of the binary tree. Returns: The maximum sum of a path in the tree. Returns negative infinity if the tree is empty. """ans=float('-inf')# Initialize the maximum path sum to negative infinity. This handles cases with all negative values.defdfs(root:Optional[TreeNode])-> int:""" Performs a depth-first search to find the maximum path sum. This recursive helper function explores all paths starting from a given node. Args: root: The current node being visited. Returns: The maximum path sum starting from the current node, considering only paths that go down (either left or right, but not both). This is crucial for preventing double-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-12-05 UTC。"],[],[]]