Skip to content

Commit 8920d82

Browse files
committed
binary-tree-maximum-path-sum
1 parent 5ce036a commit 8920d82

File tree

1 file changed

+36
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)