Skip to content

Commit d40a93f

Browse files
committed
Add solution #124
1 parent 8dfb438 commit d40a93f

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@
127127
119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy|
128128
120|[Triangle](./0120-triangle.js)|Medium|
129129
121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy|
130+
124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard|
130131
125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy|
131132
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
132133
131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 124. Binary Tree Maximum Path Sum
3+
* https://leetcode.com/problems/binary-tree-maximum-path-sum/
4+
* Difficulty: Hard
5+
*
6+
* A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the
7+
* sequence has an edge connecting them. A node can only appear in the sequence at most
8+
* once. Note that the path does not need to pass through the root.
9+
*
10+
* The path sum of a path is the sum of the node's values in the path.
11+
*
12+
* Given the root of a binary tree, return the maximum path sum of any non-empty path.
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* function TreeNode(val, left, right) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.left = (left===undefined ? null : left)
20+
* this.right = (right===undefined ? null : right)
21+
* }
22+
*/
23+
/**
24+
* @param {TreeNode} root
25+
* @return {number}
26+
*/
27+
var maxPathSum = function(root) {
28+
let result = -Infinity;
29+
30+
function traverse(node) {
31+
if (!node) return 0;
32+
const leftValue = Math.max(traverse(node.left), 0);
33+
const rightValue = Math.max(traverse(node.right), 0);
34+
result = Math.max(result, node.val + leftValue + rightValue);
35+
return node.val + Math.max(leftValue, rightValue);
36+
}
37+
38+
traverse(root);
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)