Skip to content

Commit 74f4456

Browse files
committed
solutionl: binary tree maximum path sum
1 parent 2268284 commit 74f4456

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
풀이
3+
- post order traversal dfs를 활용하여 풀이할 수 있습니다
4+
Big O
5+
- N: node의 개수
6+
- H: Tree의 높이
7+
- Time compleixty: O(N)
8+
- 모든 node를 최대 한 번 탐색합니다
9+
- Space complexity: O(H)
10+
- 재귀 호출 스택의 깊이는 H에 비례하여 증가합니다
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* type TreeNode struct {
16+
* Val int
17+
* Left *TreeNode
18+
* Right *TreeNode
19+
* }
20+
*/
21+
func maxPathSum(root *TreeNode) int {
22+
res := root.Val
23+
24+
var maxSubtreeSum func(*TreeNode) int
25+
maxSubtreeSum = func(node *TreeNode) int {
26+
// base case
27+
if node == nil {
28+
return 0
29+
}
30+
// left subtree로 내려갔을 때 구할 수 있는 maximum path sum
31+
// left subtree로 path를 내려갔을 때, left subtree가 sum에 기여하는 값이 0보다 작을 경우
32+
// left subtree로는 path를 내려가지 않는 것이 좋음
33+
// 따라서 left < 0 인 경우엔 left = 0
34+
left := maxSubtreeSum(node.Left)
35+
if left < 0 {
36+
left = 0
37+
}
38+
// right subtree도 left subtree와 동일함
39+
right := maxSubtreeSum(node.Right)
40+
if right < 0 {
41+
right = 0
42+
}
43+
// 현재 탐색하고 있는 node의 조상 node를 path에 포함하지 않고도
44+
// maxPathSum이 구해지는 경우가 있음
45+
if res < left+right+node.Val {
46+
res = left + right + node.Val
47+
}
48+
// 현재까지 계산한 subtree path sum을 부모 node에게 전달해야 함
49+
// 현재 node의 부모와 이어지는 path여야 하므로, node.Val + max(left, right)를 반환하면 됨
50+
subTreeSum := node.Val
51+
if left > right {
52+
subTreeSum += left
53+
} else {
54+
subTreeSum += right
55+
}
56+
return subTreeSum
57+
}
58+
59+
maxSubtreeSum(root)
60+
return res
61+
}

0 commit comments

Comments
 (0)