Skip to content

Commit 922d20b

Browse files
committed
#287 solution
1 parent 9a12f15 commit 922d20b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
풀이 :
3+
result를 int의 최솟값으로 초기화하고 시작
4+
5+
두가지 기능을 하는 함수 하나를 생성
6+
1. left, root->val, right의 합(하나의 path/\를 이룸)을 통해 maxSum을 업데이트
7+
2. max (left 노드 합, right 노드 합)과 root를 더해서 return
8+
-> left, right 둘 중 하나만 포함해야 상위 tree에서 path의 일부로 사용가능
9+
/\
10+
/ \
11+
/ /
12+
\
13+
이 때, 음수 노드의 합은 max(0, value)를 통해 버리고 left + right + root->val을 통해 추가적인 계산 없이 maxSum 업데이트
14+
15+
노드 개수 : N
16+
17+
TC : O(N)
18+
모든 노드 순회
19+
20+
SC : O(N)
21+
재귀 호출 스택도 노드 개수에 비례
22+
*/
23+
24+
25+
#include <limits.h>
26+
#include <algorithm>
27+
28+
using namespace std;
29+
30+
class Solution {
31+
public:
32+
int maxPathSum(TreeNode* root) {
33+
int result = INT_MIN;
34+
35+
dfs(root, result);
36+
return result;
37+
}
38+
39+
int dfs(TreeNode* root, int& maxSum) {
40+
if (!root)
41+
return 0;
42+
43+
int left = max(0, dfs(root->left, maxSum));
44+
int right = max(0, dfs(root->right, maxSum));
45+
46+
maxSum = max(maxSum, left + right + root->val);
47+
48+
return root->val + max(left, right);
49+
}
50+
};
51+
52+
struct TreeNode {
53+
int val;
54+
TreeNode *left;
55+
TreeNode *right;
56+
TreeNode() : val(0), left(nullptr), right(nullptr) {}
57+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
58+
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
59+
};

0 commit comments

Comments
 (0)