File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
binary-tree-maximum-path-sum Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You canโt perform that action at this time.
0 commit comments