Skip to content

Instantly share code, notes, and snippets.

@voxqhuy
Created July 11, 2020 05:05
Show Gist options
  • Save voxqhuy/74e8a00b4166467fe5bcfbe7c6c138a2 to your computer and use it in GitHub Desktop.
Save voxqhuy/74e8a00b4166467fe5bcfbe7c6c138a2 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/binary-tree-maximum-path-sum/
// O(n), Space O(n)
var globalMax = Int.min
func maxPathSum(_ root: TreeNode?) -> Int {
maxPath(root)
return globalMax
}
func maxPath(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
let currVal = root.val
let left = max(0, maxPath(root.left))
let right = max(0, maxPath(root.right))
globalMax = max(globalMax, left + currVal + right)
return max(left, right) + currVal
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment