剑指 Offer II 051. 节点之和最大的路径

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)
 
    }


你可能感兴趣的:(剑指 Offer II 051. 节点之和最大的路径)