Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c406fd8

Browse files
Binary tree maximum path sum
1 parent 30f0272 commit c406fd8

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

‎0124_binaryTreeMaximumPathSum.js

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,6 @@
77
* }
88
*/
99

10-
let max = Number.MIN_SAFE_INTEGER;
11-
12-
const maxValue = node => {
13-
if (node === null) return 0;
14-
15-
let leftValue = Math.max(maxValue(node.left), 0);
16-
let rightValue = Math.max(maxValue(node.right), 0);
17-
18-
max = Math.max(max, node.val + leftValue + rightValue);
19-
20-
return node.val + Math.max(leftValue, rightValue);
21-
};
22-
2310
/**
2411
* @param {TreeNode} root Head of the binary tree.
2512
* @return {max} Maximum path sum.
@@ -29,6 +16,18 @@ const maxValue = node => {
2916
* Time O(k) - where k is height of tree.
3017
*/
3118
const maxPathSum = root => {
19+
let max = Number.MIN_SAFE_INTEGER;
20+
const maxValue = node => {
21+
if (node === null) return 0;
22+
23+
let leftValue = Math.max(maxValue(node.left), 0);
24+
let rightValue = Math.max(maxValue(node.right), 0);
25+
26+
max = Math.max(max, node.val + leftValue + rightValue);
27+
28+
return node.val + Math.max(leftValue, rightValue);
29+
};
30+
3231
maxValue(root);
3332

3433
return max;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /