Skip to content

Commit de828da

Browse files
committed
Binary Tree Maximum Path Sum / 심화
1 parent 8228c60 commit de828da

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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 maxSum = -Infinity;
15+
16+
function dfs(node) {
17+
if (!node) return 0;
18+
19+
const left = Math.max(dfs(node.left), 0);
20+
const right = Math.max(dfs(node.right), 0);
21+
22+
const currentSum = node.val + left + right;
23+
24+
maxSum = Math.max(maxSum, currentSum);
25+
26+
return node.val + Math.max(left, right);
27+
}
28+
29+
dfs(root);
30+
return maxSum;
31+
};

0 commit comments

Comments
 (0)