Skip to content

Commit

Permalink
Merge pull request neetcode-gh#958 from MaratKhakim/124-BT-Max-Path-Kt
Browse files Browse the repository at this point in the history
Kotlin: 124. Binary Tree Maximum Path Sum
  • Loading branch information
Ahmad-A0 authored Aug 29, 2022
2 parents a1a63b9 + ed0d89a commit 8ef6dc1
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions kotlin/124-Binary-Tree-Maximumu-Path-Sum.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun maxPathSum(root: TreeNode?): Int {
val res = IntArray(1) {Int.MIN_VALUE}
maxPathSum(root, res)
return res[0]
}

fun maxPathSum(root: TreeNode?, res: IntArray): Int {
if (root == null)
return 0

val left = Math.max(0, maxPathSum(root.left, res))
val right = Math.max(0, maxPathSum(root.right, res))
res[0] = Math.max(res[0], root.`val` + left + right)

return root.`val` + Math.max(left, right)
}
}

0 comments on commit 8ef6dc1

Please sign in to comment.