Skip to content

Commit ce276e8

Browse files
committed
add max path sum in binary tree question
1 parent 19da303 commit ce276e8

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time O(n)
2+
// Space O(log n) because we are dealing with a binary tree and at most
3+
// we will have log n calls on the call stack
4+
function maxPathSum(tree) {
5+
const [_, maxSum] = findMaxSum(tree);
6+
return maxSum;
7+
}
8+
9+
function findMaxSum(tree) {
10+
if (tree === null) return [0, -Infinity];
11+
12+
const [leftMaxSumAsBranch, leftMaxPathSum] = findMaxSum(tree.left);
13+
const [rightMaxSumAsBranch, rightMaxPathSum] = findMaxSum(tree.right);
14+
const maxChildSumAsBranch = Math.max(leftMaxSumAsBranch, rightMaxSumAsBranch);
15+
16+
const { value } = tree;
17+
const maxSumAsBranch = Math.max(maxChildSumAsBranch + value, value);
18+
const maxSumAsRootNode = Math.max(
19+
leftMaxSumAsBranch + value + rightMaxSumAsBranch,
20+
maxSumAsBranch
21+
);
22+
const maxPathSum = Math.max(
23+
leftMaxPathSum,
24+
rightMaxPathSum,
25+
maxSumAsRootNode
26+
);
27+
28+
return [maxSumAsBranch, maxPathSum];
29+
}

0 commit comments

Comments
 (0)