File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * public class TreeNode {
4+ * public var val: Int
5+ * public var left: TreeNode?
6+ * public var right: TreeNode?
7+ * public init() { self.val = 0; self.left = nil; self.right = nil; }
8+ * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
9+ * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
10+ * self.val = val
11+ * self.left = left
12+ * self.right = right
13+ * }
14+ * }
15+ */
16+ class Solution {
17+ var globalMax : Int = Int . min
18+
19+ // Return max path that '''ends at''' a particular node
20+ private func ends( at node: TreeNode ? ) -> Int {
21+ // Base case
22+ guard let node = node else { return 0 }
23+
24+ // Recursive cases
25+ // MAX with 0, to shorten negative paths
26+ let leftMaxPath = max ( ends ( at: node. left) , 0 )
27+ let rightMaxPath = max ( ends ( at: node. right) , 0 )
28+
29+ let pathIncludingNode = leftMaxPath + node. val + rightMaxPath
30+ globalMax = max ( globalMax, pathIncludingNode)
31+
32+ let pathEndingAtNode = max ( leftMaxPath, rightMaxPath) + node. val
33+ return pathEndingAtNode
34+ }
35+
36+ func maxPathSum( _ root: TreeNode ? ) -> Int {
37+ ends ( at: root)
38+ return globalMax
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments