Skip to content

Commit 785467d

Browse files
authored
Create 124-binary-tree-maximum-path-sum.js
1 parent 65662f5 commit 785467d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

124-binary-tree-maximum-path-sum.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number}
11+
*/
12+
const maxPathSum = function(root) {
13+
let obj = {
14+
max: Number.MIN_SAFE_INTEGER
15+
}
16+
traverse(root, obj)
17+
18+
return obj.max
19+
};
20+
21+
function traverse(node, obj) {
22+
if(node === null) return 0
23+
let left = Math.max(0, traverse(node.left, obj))
24+
let right = Math.max(0, traverse(node.right, obj))
25+
obj.max = Math.max(obj.max, node.val+left+right)
26+
return node.val + Math.max(left, right)
27+
}
28+

0 commit comments

Comments
 (0)