forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0124-binary-tree-maximum-path-sum.swift
40 lines (35 loc) · 1.26 KB
/
0124-binary-tree-maximum-path-sum.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
classSolution{
varglobalMax:Int=Int.min
// Return max path that '''ends at''' a particular node
privatefunc ends(at node:TreeNode?)->Int{
// Base case
guardlet node = node else{return0}
// Recursive cases
// MAX with 0, to shorten negative paths
letleftMaxPath=max(ends(at: node.left),0)
letrightMaxPath=max(ends(at: node.right),0)
letpathIncludingNode= leftMaxPath + node.val + rightMaxPath
globalMax =max(globalMax, pathIncludingNode)
letpathEndingAtNode=max(leftMaxPath, rightMaxPath)+ node.val
return pathEndingAtNode
}
func maxPathSum(_ root:TreeNode?)->Int{
ends(at: root)
return globalMax
}
}