Skip to content

Commit 8ef6dc1

Browse files
authored
Merge pull request neetcode-gh#958 from MaratKhakim/124-BT-Max-Path-Kt
Kotlin: 124. Binary Tree Maximum Path Sum
2 parents a1a63b9 + ed0d89a commit 8ef6dc1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Example:
3+
* var ti = TreeNode(5)
4+
* var v = ti.`val`
5+
* Definition for a binary tree node.
6+
* class TreeNode(var `val`: Int) {
7+
* var left: TreeNode? = null
8+
* var right: TreeNode? = null
9+
* }
10+
*/
11+
class Solution {
12+
fun maxPathSum(root: TreeNode?): Int {
13+
val res = IntArray(1) {Int.MIN_VALUE}
14+
maxPathSum(root, res)
15+
return res[0]
16+
}
17+
18+
fun maxPathSum(root: TreeNode?, res: IntArray): Int {
19+
if (root == null)
20+
return 0
21+
22+
val left = Math.max(0, maxPathSum(root.left, res))
23+
val right = Math.max(0, maxPathSum(root.right, res))
24+
res[0] = Math.max(res[0], root.`val` + left + right)
25+
26+
return root.`val` + Math.max(left, right)
27+
}
28+
}

0 commit comments

Comments
 (0)