File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ import ds.TreeNode
2
+
3
+ /*
4
+ Definition of TreeNode:
5
+
6
+ data class TreeNode(
7
+ var value: Int,
8
+ var left: TreeNode? = null,
9
+ var right: TreeNode? = null
10
+ )
11
+ */
12
+
13
+ fun maxPathSum (root : TreeNode ? ): Int {
14
+ // In Kotlin, global variable is bad practice.
15
+ // So, we use a mutable list to store the max sum and access it by reference.
16
+ var maxSum = mutableListOf (Int .MIN_VALUE )
17
+ maxPathSumHelper(root, maxSum)
18
+ return maxSum[0 ]
19
+ }
20
+
21
+ fun maxPathSumHelper (node : TreeNode ? , maxSum : MutableList <Int >): Int {
22
+ // Base case: null nodes have no path sum.
23
+ if (node == null ) {
24
+ return 0
25
+ }
26
+ // Collect the maximum gain we can attain from the left and right
27
+ // subtrees, setting them to 0 if they're negative.
28
+ val leftSum = Math .max(maxPathSumHelper(node.left, maxSum), 0 )
29
+ val rightSum = Math .max(maxPathSumHelper(node.right, maxSum), 0 )
30
+ // Update the overall maximum path sum if the current path sum is
31
+ // larger.
32
+ maxSum[0 ] = Math .max(maxSum[0 ], node.value + leftSum + rightSum)
33
+ // Return the maximum sum of a single, continuous path with the
34
+ // current node as an endpoint.
35
+ return node.value + Math .max(leftSum, rightSum)
36
+ }
You can’t perform that action at this time.
0 commit comments