Skip to content

Commit d21aacc

Browse files
authored
Merge pull request neetcode-gh#1134 from Mahim1997/dev/124_swift
124. Binary Tree Maximum Path Sum
2 parents 051d9c0 + 146b72c commit d21aacc

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

0 commit comments

Comments
 (0)