## 題解 ```python= # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: Optional[TreeNode]) -> int: max_path = float("-inf") def dfs(root: TreeNode): nonlocal max_path if not root: return 0 left_sum = max(dfs(root.left),0) right_sum = max(dfs(root.right),0) max_path = max(max_path,root.val + left_sum + right_sum) # 計算最大路徑總和 return root.val + max(left_sum,right_sum) # 選擇最大的子樹,避免路徑分岔 dfs(root) return max_path ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up