Skip to content

Commit 960ff46

Browse files
committed
binary-tree-maximum-path-sum
1 parent 5f9c5fd commit 960ff46

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* https://leetcode.com/problems/binary-tree-maximum-path-sum/
3+
* Definition for a binary tree node.
4+
* function TreeNode(val, left, right) {
5+
* this.val = (val===undefined ? 0 : val)
6+
* this.left = (left===undefined ? null : left)
7+
* this.right = (right===undefined ? null : right)
8+
* }
9+
*/
10+
/**
11+
* @param {TreeNode} root
12+
* @return {number}
13+
*/
14+
var maxPathSum = function (root) {
15+
let maxSum = -Infinity; // global max
16+
17+
function dfs(node) {
18+
if (!node) return 0;
19+
20+
// ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์—์„œ ์ตœ๋Œ€ ๊ฒฝ๋กœ ํ•ฉ์„ ๊ตฌํ•œ๋‹ค
21+
// ์Œ์ˆ˜๋ฉด 0์œผ๋กœ ์น˜ํ™˜ (ํ•ด๋‹น ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š๋Š”๊ฒŒ ๋” ์ด๋“์ธ ๊ฒฝ์šฐ)
22+
let leftMax = Math.max(0, dfs(node.left));
23+
let rightMax = Math.max(0, dfs(node.right));
24+
25+
// ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋ฃจํŠธ๋กœ ํ•˜๋Š” ๊ฒฝ๋กœ์—์„œ ์ตœ๋Œ€๊ฐ’์„ ๊ณ„์‚ฐ (left + node + right)
26+
let currentMax = leftMax + node.val + rightMax;
27+
28+
// global ์ตœ๋Œ€๊ฐ’ ๊ฐฑ์‹ 
29+
maxSum = Math.max(maxSum, currentMax);
30+
31+
// ๋ถ€๋ชจ ๋…ธ๋“œ๋กœ return ์‹œ: ํ•œ์ชฝ ๋ฐฉํ–ฅ์œผ๋กœ๋งŒ ์„ ํƒ ๊ฐ€๋Šฅ
32+
return node.val + Math.max(leftMax, rightMax);
33+
}
34+
35+
dfs(root);
36+
return maxSum;
37+
};

0 commit comments

Comments
ย (0)