剑指 Offer II 051. 节点之和最大的路径
2022-08-31 本文已影响0人
邦_
DFS
func maxPathSum(_ root: TreeNode?) -> Int {
var res = Int.min
let _ = dfs(root,&res)
return res
}
func dfs(_ root: TreeNode?,_ res: inout Int) -> Int{
if root == nil {
return 0
}
let left = max(0, dfs(root?.left, &res))
let right = max(0, dfs(root?.right, &res))
let sum = left + right + root!.val
res = max(res, sum)
return root!.val + max(left, right)
}