File tree 1 file changed +29
-0
lines changed
1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time O(n)
2
+ // Space O(log n) because we are dealing with a binary tree and at most
3
+ // we will have log n calls on the call stack
4
+ function maxPathSum ( tree ) {
5
+ const [ _ , maxSum ] = findMaxSum ( tree ) ;
6
+ return maxSum ;
7
+ }
8
+
9
+ function findMaxSum ( tree ) {
10
+ if ( tree === null ) return [ 0 , - Infinity ] ;
11
+
12
+ const [ leftMaxSumAsBranch , leftMaxPathSum ] = findMaxSum ( tree . left ) ;
13
+ const [ rightMaxSumAsBranch , rightMaxPathSum ] = findMaxSum ( tree . right ) ;
14
+ const maxChildSumAsBranch = Math . max ( leftMaxSumAsBranch , rightMaxSumAsBranch ) ;
15
+
16
+ const { value } = tree ;
17
+ const maxSumAsBranch = Math . max ( maxChildSumAsBranch + value , value ) ;
18
+ const maxSumAsRootNode = Math . max (
19
+ leftMaxSumAsBranch + value + rightMaxSumAsBranch ,
20
+ maxSumAsBranch
21
+ ) ;
22
+ const maxPathSum = Math . max (
23
+ leftMaxPathSum ,
24
+ rightMaxPathSum ,
25
+ maxSumAsRootNode
26
+ ) ;
27
+
28
+ return [ maxSumAsBranch , maxPathSum ] ;
29
+ }
You can’t perform that action at this time.
0 commit comments