forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsungjinwi.cpp
More file actions
59 lines (45 loc) ยท 1.68 KB
/
sungjinwi.cpp
File metadata and controls
59 lines (45 loc) ยท 1.68 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
ํ์ด :
result๋ฅผ int์ ์ต์๊ฐ์ผ๋ก ์ด๊ธฐํํ๊ณ ์์
๋๊ฐ์ง ๊ธฐ๋ฅ์ ํ๋ ํจ์ ํ๋๋ฅผ ์์ฑ
1. left, root->val, right์ ํฉ(ํ๋์ path/\๋ฅผ ์ด๋ฃธ)์ ํตํด maxSum์ ์
๋ฐ์ดํธ
2. max (left ๋
ธ๋ ํฉ, right ๋
ธ๋ ํฉ)๊ณผ root๋ฅผ ๋ํด์ return
-> left, right ๋ ์ค ํ๋๋ง ํฌํจํด์ผ ์์ tree์์ path์ ์ผ๋ถ๋ก ์ฌ์ฉ๊ฐ๋ฅ
/\
/ \
/ /
\
์ด ๋, ์์ ๋
ธ๋์ ํฉ์ max(0, value)๋ฅผ ํตํด ๋ฒ๋ฆฌ๊ณ left + right + root->val์ ํตํด ์ถ๊ฐ์ ์ธ ๊ณ์ฐ ์์ด maxSum ์
๋ฐ์ดํธ
๋
ธ๋ ๊ฐ์ : N
TC : O(N)
๋ชจ๋ ๋
ธ๋ ์ํ
SC : O(N)
์ฌ๊ท ํธ์ถ ์คํ๋ ๋
ธ๋ ๊ฐ์์ ๋น๋ก
*/
#include <limits.h>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxPathSum(TreeNode* root) {
int result = INT_MIN;
dfs(root, result);
return result;
}
int dfs(TreeNode* root, int& maxSum) {
if (!root)
return 0;
int left = max(0, dfs(root->left, maxSum));
int right = max(0, dfs(root->right, maxSum));
maxSum = max(maxSum, left + right + root->val);
return root->val + max(left, right);
}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};