File tree 1 file changed +14
-13
lines changed
solution/0100-0199/0124.Binary Tree Maximum Path Sum
1 file changed +14
-13
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- private int max = Integer .MIN_VALUE ;
2
+ private int val = Integer .MIN_VALUE ;
3
+
3
4
public int maxPathSum (TreeNode root ) {
4
- helper (root );
5
- return max ;
5
+ dfs (root );
6
+ return val ;
6
7
}
7
- private int helper (TreeNode root ) {
8
- if (root == null ) return 0 ;
9
- if (root .left == null && root .right == null ) {
10
- max = Math .max (max , root .val );
11
- return root .val ;
8
+
9
+ public int dfs (TreeNode root ) {
10
+ if (root == null ) {
11
+ return 0 ;
12
12
}
13
- int left = helper (root .left );
14
- int right = helper (root .right );
15
- int currSum = Math .max (Math .max (left + root .val , right + root .val ), root .val );
16
- max = Math .max (Math .max (currSum , left + right + root .val ), max );
17
- return currSum ;
13
+ int left = Math .max (0 , dfs (root .left ));
14
+ int right = Math .max (0 , dfs (root .right ));
15
+ int val1 = root .val + left + right ;
16
+ int val2 = root .val + Math .max (0 , Math .max (left , right ));
17
+ val = Math .max (val , val1 );
18
+ return val2 ;
18
19
}
19
20
}
You can’t perform that action at this time.
0 commit comments