Skip to content

Commit 47cc65f

Browse files
authored
Merge pull request #37 from jeantimex/binary-tree-maximum-path-sum
Added binary tree max path sum problem.
2 parents a41dcd9 + e196143 commit 47cc65f

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
3333
- [Flatten Binary Tree to Linked List](src/tree/flatten-binary-tree-to-linked-list.js)
3434
- [Populating Next Right Pointers in Each Node](src/tree/populating-next-right-pointers-in-each-node.js)
3535
- [Populating Next Right Pointers in Each Node II](src/tree/populating-next-right-pointers-in-each-node-ii.js)
36+
- [Binary Tree Maximum Path Sum](src/tree/binary-tree-maximum-path-sum.js)
3637

3738
### Dynamic Programming
3839

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { assert } from 'chai';
2+
import { serializeTree, deserializeTree } from 'utils/tree-util';
3+
import maxPathSum from '../binary-tree-maximum-path-sum';
4+
5+
describe('Binary Tree Maximum Path Sum', () => {
6+
const testCases = [['1', 1], ['1,2,3', 6], ['1,-1,-2', 1], ['0,0,1', 1]];
7+
8+
testCases.map((testCase, index) => {
9+
it(`should calculate the max path sum for tree ${testCase[0]}`, () => {
10+
const root = deserializeTree(testCase[0]);
11+
const expected = testCase[1];
12+
const actual = maxPathSum(root);
13+
assert.equal(actual, expected);
14+
});
15+
});
16+
});
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Given a binary tree, find the maximum path sum.
3+
*
4+
* For this problem, a path is defined as any sequence of nodes from some starting node to any node
5+
* in the tree along the parent-child connections. The path must contain at least one node and does
6+
* not need to go through the root.
7+
*
8+
* For example:
9+
* Given the below binary tree,
10+
*
11+
* 1
12+
* / \
13+
* 2 3
14+
*
15+
* Return 6.
16+
*
17+
* The helper function returns the max path including the current node's value.
18+
*/
19+
20+
/**
21+
* @param {TreeNode} root
22+
* @return {number}
23+
*/
24+
const maxPathSum = root => {
25+
const helper = root => {
26+
if (!root) {
27+
return 0;
28+
}
29+
30+
const left = Math.max(helper(root.left), 0);
31+
const right = Math.max(helper(root.right), 0);
32+
33+
max = Math.max(max, root.val + left + right);
34+
35+
return root.val + Math.max(left, right);
36+
};
37+
38+
let max = Number.MIN_SAFE_INTEGER;
39+
helper(root);
40+
return max;
41+
};
42+
43+
export default maxPathSum;

0 commit comments

Comments
 (0)