192 words
1 minute
日拱两卒(六)
2026-07-28

50#

二叉树中的最大路径和。

维护每个节点的左右两条链。

因为有负数,注意和零比较。

class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
if root == None:
return 0
N = 3 * 10000 + 10
ans = -N * 1000
s = dict()
def dfs(u):
nonlocal ans
if u.left is None:
s[(u, 0)] = 0
if u.right is None:
s[(u, 1)] = 0
if u.left:
dfs(u.left)
s[(u, 0)] = max(0, max(s[(u.left, 0)], s[(u.left, 1)]) + u.left.val)
if u.right:
dfs(u.right)
s[(u, 1)] = max(0, max(s[(u.right, 0)], s[(u.right, 1)]) + u.right.val)
ans = max(ans, u.val + s[(u, 0)] + s[(u, 1)])
dfs(root)
return ans

49#

二叉树的最近公共祖先。

简单递归。

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None or root == p or root == q:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if l and r:
return root
if l:
return self.lowestCommonAncestor(l, p, q)
if r:
return self.lowestCommonAncestor(r, p, q)
return None