# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def dfs(root):# dfs表示从当前节点往下走的某条路的最大值
nonlocal res
if not root: return 0
a=dfs(root.left)
b= dfs(root.right)
res= max(res,root.val+a+b)
return max(0,root.val+max(a,b))
res=float("-inf")
dfs(root)
return res
124. 二叉树中的最大路径和
最新推荐文章于 2025-09-01 18:18:00 发布
本文深入探讨了寻找二叉树中最大路径和的算法实现,通过深度优先搜索策略,递归地计算从每个节点出发的最大路径值,最终找到整棵树中的最大路径和。
1万+

被折叠的 条评论
为什么被折叠?



