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)
}
网友评论