-
Notifications
You must be signed in to change notification settings - Fork 44
/
Problem94.js
38 lines (32 loc) · 1.07 KB
/
Problem94.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Problem 94
//
// This problem was asked by Google.
//
// Given a binary tree of integers, find the maximum path sum between two nodes. The path must go through at least one node, and does not need to go through the root.
//
// https://leetcode.com/problems/binary-tree-maximum-path-sum/
//
// O(N) Time complexity
// O(d) Space complexity
// N is the number of nodes in the tree. d is the depth of the tree
/**
* Finds the maximum path sum between two nodes
* @param {TreeNode} root
* @return {number}
*/
function maxPathSum(root) {
// set result in the first element of max
const max = [Number.MIN_SAFE_INTEGER];
maxPathSumHelper(root, max);
return max[0];
}
function maxPathSumHelper(root, max) {
if (root === null) return 0;
// do not include negatives to our sum
const leftMax = Math.max(0, maxPathSumHelper(root.left, max));
const rightMax = Math.max(0, maxPathSumHelper(root.right, max));
max[0] = Math.max(max[0], leftMax + rightMax + root.val);
// return the sum of branch
return root.val + Math.max(leftMax, rightMax);
}
export default maxPathSum;