File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
binary-tree-maximum-path-sum Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TreeNode {
2
+ val : number ;
3
+ left : TreeNode | null ;
4
+ right : TreeNode | null ;
5
+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
6
+ this . val = val === undefined ? 0 : val ;
7
+ this . left = left === undefined ? null : left ;
8
+ this . right = right === undefined ? null : right ;
9
+ }
10
+ }
11
+
12
+ // TC: O(n)
13
+ // SC: O(n)
14
+ function maxPathSum ( root : TreeNode | null ) : number {
15
+ let maxSum = - Infinity ;
16
+
17
+ const dfs = ( node : TreeNode | null ) => {
18
+ if ( ! node ) return 0 ;
19
+
20
+ const leftMax = Math . max ( dfs ( node . left ) , 0 ) ;
21
+ const rightMax = Math . max ( dfs ( node . right ) , 0 ) ;
22
+
23
+ maxSum = Math . max ( node . val + leftMax + rightMax , maxSum ) ;
24
+
25
+ return node . val + Math . max ( leftMax , rightMax ) ;
26
+ } ;
27
+
28
+ dfs ( root ) ;
29
+ return maxSum ;
30
+ }
You can’t perform that action at this time.
0 commit comments