File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * @param {TreeNode } root
11
+ * @return {number }
12
+ */
13
+ var maxPathSum = function ( root ) {
14
+ const res = [ root . val ] ;
15
+
16
+ // return max path sum without split
17
+ function dfs ( root ) {
18
+ if ( ! root ) {
19
+ return 0 ;
20
+ }
21
+
22
+ let leftMax = dfs ( root . left ) ;
23
+ let rightMax = dfs ( root . right ) ;
24
+ leftMax = Math . max ( leftMax , 0 ) ;
25
+ rightMax = Math . max ( rightMax , 0 ) ;
26
+
27
+ // compute max path sum WITH split
28
+ res [ 0 ] = Math . max ( res [ 0 ] , root . val + leftMax + rightMax ) ;
29
+
30
+ return root . val + Math . max ( leftMax , rightMax ) ;
31
+ }
32
+
33
+ dfs ( root ) ;
34
+ return res [ 0 ] ;
35
+ } ;
You can’t perform that action at this time.
0 commit comments