# 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 classSolution: defmaxPathSum(self, root: Optional[TreeNode]) -> int: ans = -inf
defdfs(root: Optional[TreeNode]) -> int: nonlocal ans
if root isNone: return0
left = max(0, dfs(root.left)) right = max(0, dfs(root.right))
ans = max(ans, left + right + root.val) returnmax(left, right) + root.val dfs(root)
# 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 classSolution: defdiameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: ans = 0
defdfs(root: Optional[TreeNode]) -> int: nonlocal ans if root isNone: return0
left = dfs(root.left) right = dfs(root.right)
ans = max(ans, left + right + 1) returnmax(left, right) + 1 dfs(root) return ans - 1# 链的长度 = 节点数目 - 1