Skip to content

Commit 42e321e

Browse files
Jeehay28Jeehay28
authored andcommitted
Add binary-tree-maximum-path-sum solution in TS
1 parent 58cac9c commit 42e321e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
// TC: O(n)
13+
// SC: O(n)
14+
function maxPathSum(root: TreeNode | null): number {
15+
let maxSum = -Infinity;
16+
17+
const dfs = (node: TreeNode | null) => {
18+
if (!node) return 0;
19+
20+
const leftMax = Math.max(dfs(node.left), 0);
21+
const rightMax = Math.max(dfs(node.right), 0);
22+
23+
maxSum = Math.max(node.val + leftMax + rightMax, maxSum);
24+
25+
return node.val + Math.max(leftMax, rightMax);
26+
};
27+
28+
dfs(root);
29+
return maxSum;
30+
}

0 commit comments

Comments
 (0)