forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdalma.kt
More file actions
35 lines (27 loc) Β· 1 KB
/
jdalma.kt
File metadata and controls
35 lines (27 loc) Β· 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import kotlin.math.max
class `binary-tree-maximum-path-sum` {
/**
* TC: O(n), SC: O(log n)
*/
fun maxPathSum(root: TreeNode?): Int {
if (root == null) return 0
var max = root.`val` // λΆλͺ¨ λ
Έλμ 2κ°μ μμ λ
Έλμ ν©μ μ μ λ³μλ‘ κ°±μ νλ€.
fun dfs(node: TreeNode?): Int {
if (node == null) return 0
val left = max(dfs(node.left), 0)
val right = max(dfs(node.right), 0)
max = max(node.`val` + left + right, max)
return node.`val` + max(left, right) // νμ¬ λ
Έλμ 2κ°μ μμ λ
Έλ μ€ μ΅λμ κ°μ λ°ννλ€.
}
dfs(root)
return max
}
@Test
fun `μ΄μ§ νΈλ¦¬μ μ΅λ κ²½λ‘ ν©μ λ°ννλ€`() {
maxPathSum(TreeNode.of(-10,9,20,null,null,15,7)) shouldBe 42
maxPathSum(TreeNode.of(1,9,20,null,null,15,7)) shouldBe 45
}
}