forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrumbs22.cpp
More file actions
27 lines (22 loc) ยท 909 Bytes
/
crumbs22.cpp
File metadata and controls
27 lines (22 loc) ยท 909 Bytes
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
class Solution {
public:
int maxPathSum(TreeNode* root) {
int res = INT_MIN;
dfs(root, res);
return res;
}
int dfs(TreeNode* root, int& res) {
if (!root)
return 0;
// ์ข์ธก ๋ถ๋ถํธ๋ฆฌ, ์ฐ์ธก ๋ถ๋ถํธ๋ฆฌ๋ฅผ ๊ฐ๊ฐ ๊ณ์ฐํ ๋ dfs์ '๋ฐํ๊ฐ'์ ํ์ฉ
// ์์๊ฐ์ด ๋์ฌ ๊ฒฝ์ฐ๋ 0์ผ๋ก ๋์ฒดํจ
int left = max(0, dfs(root->left, res));
int right = max(0, dfs(root->right, res));
// ์ต์ข
๋ฐํํ ๊ฐ ์
๋ฐ์ดํธ
// ์ข์ธก ํธ๋ฆฌ, ์ฐ์ธก ํธ๋ฆฌ, ๋ฃจํธ ๋
ธ๋๋ฅผ ๋ชจ๋ ํต๊ณผํ๋ ๊ฒฝ๋ก๊ฐ ํ์ฌ๊น์ง ์ต๋๊ฐ์ธ์ง ๋น๊ตํด์ ๊ฐฑ์
res = max(res, root->val + left + right);
// ์์ ๋
ธ๋๋ก ์ ๋ฌ๋๋ ๊ฐ์ root์ ๊ฐ์ ํฌํจํ๋ ๊ฒฝ๋ก์ ๊ฐ์ด๋ค
// ๋ฐ๋ผ์ ์ข์ธก ํธ๋ฆฌ ํน์ ์ฐ์ธก ํธ๋ฆฌ ์ค ํ๋์ ๊ฒฝ๋ก๋ง์ ์ ํํด์ ํต๊ณผํ ์ ์๋ค
return root->val + max(left, right);
}
};