Skip to content

Commit 1ef9a64

Browse files
authored
[ PS ] : Binary Tree Maximum Path Sum
1 parent 102f5ec commit 1ef9a64

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
const maxPathSum = function (root) {
14+
let max = root.val;
15+
16+
function getMaxSum(node) {
17+
if (!node) return 0;
18+
19+
const leftVal = Math.max(getMaxSum(node.left), 0);
20+
const rightVal = Math.max(getMaxSum(node.right), 0);
21+
22+
max = Math.max(node.val + leftVal + rightVal, max);
23+
24+
return node.val + Math.max(leftVal, rightVal);
25+
}
26+
27+
getMaxSum(root);
28+
29+
return max;
30+
};
31+
32+
// 시간복잡도: O(n)
33+
// 공간복잡도: O(h) (h: 트리의 높이, 즉 재귀 스택 깊이)

0 commit comments

Comments
 (0)