Skip to content

Commit 86a8b13

Browse files
committed
Feat: 124. Binary Tree Maximum Path Sum
1 parent 7c15d7e commit 86a8b13

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
/**
13+
* https://leetcode.com/problems/binary-tree-maximum-path-sum
14+
* T.C. O(n)
15+
* S.C. O(n)
16+
*/
17+
function maxPathSum(root: TreeNode | null): number {
18+
let max = -Infinity;
19+
20+
function dfs(node: TreeNode | null): number {
21+
if (!node) return 0;
22+
23+
const left = Math.max(0, dfs(node.left));
24+
const right = Math.max(0, dfs(node.right));
25+
26+
max = Math.max(max, node.val + left + right);
27+
28+
return node.val + Math.max(left, right);
29+
}
30+
31+
dfs(root);
32+
33+
return max;
34+
}
35+
36+
/**
37+
* iterative using stack
38+
* T.C. O(n)
39+
* S.C. O(n)
40+
*/
41+
function maxPathSum(root: TreeNode | null): number {
42+
let max = -Infinity;
43+
const stack: Array<TreeNode | null> = [root];
44+
const memo = new Map<TreeNode, number>();
45+
46+
while (stack.length) {
47+
const node = stack.pop();
48+
49+
if (!node) continue;
50+
51+
if (memo.has(node)) {
52+
const left = Math.max(0, node.left ? memo.get(node.left)! : 0);
53+
const right = Math.max(0, node.right ? memo.get(node.right)! : 0);
54+
55+
max = Math.max(max, node.val + left + right);
56+
57+
memo.set(node, node.val + Math.max(left, right));
58+
} else {
59+
stack.push(node, node.right, node.left);
60+
memo.set(node, 0);
61+
}
62+
}
63+
64+
return max;
65+
}

0 commit comments

Comments
 (0)