Skip to content

Commit 3f6e23a

Browse files
committed
Feat: #287
1 parent a648b97 commit 3f6e23a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public:
3+
int maxPathSum(TreeNode* root) {
4+
int res = INT_MIN;
5+
6+
dfs(root, res);
7+
return res;
8+
}
9+
10+
int dfs(TreeNode* root, int& res) {
11+
if (!root)
12+
return 0;
13+
14+
// ์ขŒ์ธก ๋ถ€๋ถ„ํŠธ๋ฆฌ, ์šฐ์ธก ๋ถ€๋ถ„ํŠธ๋ฆฌ๋ฅผ ๊ฐ๊ฐ ๊ณ„์‚ฐํ•  ๋•Œ dfs์˜ '๋ฐ˜ํ™˜๊ฐ’'์„ ํ™œ์šฉ
15+
// ์Œ์ˆ˜๊ฐ’์ด ๋‚˜์˜ฌ ๊ฒฝ์šฐ๋Š” 0์œผ๋กœ ๋Œ€์ฒดํ•จ
16+
int left = max(0, dfs(root->left, res));
17+
int right = max(0, dfs(root->right, res));
18+
19+
// ์ตœ์ข… ๋ฐ˜ํ™˜ํ•  ๊ฐ’ ์—…๋ฐ์ดํŠธ
20+
// ์ขŒ์ธก ํŠธ๋ฆฌ, ์šฐ์ธก ํŠธ๋ฆฌ, ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๋ชจ๋‘ ํ†ต๊ณผํ•˜๋Š” ๊ฒฝ๋กœ๊ฐ€ ํ˜„์žฌ๊นŒ์ง€ ์ตœ๋Œ“๊ฐ’์ธ์ง€ ๋น„๊ตํ•ด์„œ ๊ฐฑ์‹ 
21+
res = max(res, root->val + left + right);
22+
23+
// ์ƒ์œ„ ๋…ธ๋“œ๋กœ ์ „๋‹ฌ๋˜๋Š” ๊ฐ’์€ root์˜ ๊ฐ’์„ ํฌํ•จํ•˜๋Š” ๊ฒฝ๋กœ์˜ ๊ฐ’์ด๋‹ค
24+
// ๋”ฐ๋ผ์„œ ์ขŒ์ธก ํŠธ๋ฆฌ ํ˜น์€ ์šฐ์ธก ํŠธ๋ฆฌ ์ค‘ ํ•˜๋‚˜์˜ ๊ฒฝ๋กœ๋งŒ์„ ์„ ํƒํ•ด์„œ ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ๋‹ค
25+
return root->val + max(left, right);
26+
}
27+
};

0 commit comments

Comments
ย (0)