Created
July 11, 2020 05:05
-
-
Save voxqhuy/74e8a00b4166467fe5bcfbe7c6c138a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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