Skip to content

Commit e6e23e6

Browse files
committed
feat: 124. Binary Tree Maximum Path Sum
1 parent 88784f2 commit e6e23e6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {number}
15+
*/
16+
var maxPathSum = function (root) {
17+
let answer = Number.MIN_SAFE_INTEGER;
18+
19+
const dfs = (current) => {
20+
const candidates = [current.val];
21+
22+
if (current.left) {
23+
dfs(current.left);
24+
candidates.push(current.left.val + current.val);
25+
}
26+
27+
if (current.right) {
28+
dfs(current.right);
29+
candidates.push(current.right.val + current.val);
30+
}
31+
32+
// 현재 노드가 루트일 경우
33+
if (current.left && current.right) {
34+
answer = Math.max(
35+
answer,
36+
current.left.val + current.right.val + current.val
37+
);
38+
}
39+
40+
current.val = Math.max(...candidates);
41+
answer = Math.max(answer, current.val);
42+
};
43+
44+
dfs(root);
45+
46+
return answer;
47+
};

0 commit comments

Comments
 (0)