Skip to content

Commit 3dc9850

Browse files
committed
문제 추가
1 parent cfbe1ce commit 3dc9850

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
import kotlin.math.max
6+
7+
class `binary-tree-maximum-path-sum` {
8+
9+
/**
10+
* TC: O(n), SC: O(log n)
11+
*/
12+
fun maxPathSum(root: TreeNode?): Int {
13+
if (root == null) return 0
14+
var max = root.`val` // 부모 노드와 2개의 자식 노드의 합을 전역 변수로 갱신한다.
15+
16+
fun dfs(node: TreeNode?): Int {
17+
if (node == null) return 0
18+
19+
val left = max(dfs(node.left), 0)
20+
val right = max(dfs(node.right), 0)
21+
22+
max = max(node.`val` + left + right, max)
23+
return node.`val` + max(left, right) // 현재 노드와 2개의 자식 노드 중 최대의 값을 반환한다.
24+
}
25+
26+
dfs(root)
27+
return max
28+
}
29+
30+
@Test
31+
fun `이진 트리의 최대 경로 합을 반환한다`() {
32+
maxPathSum(TreeNode.of(-10,9,20,null,null,15,7)) shouldBe 42
33+
maxPathSum(TreeNode.of(1,9,20,null,null,15,7)) shouldBe 45
34+
}
35+
}

0 commit comments

Comments
 (0)