File tree Expand file tree Collapse file tree 1 file changed +16
-15
lines changed
124_binary_tree_maximum_path_sum Expand file tree Collapse file tree 1 file changed +16
-15
lines changed Original file line number Diff line number Diff line change @@ -8,35 +8,36 @@ struct TreeNode {
8
8
struct TreeNode * right ;
9
9
};
10
10
11
- static int partition ( struct TreeNode * node , int * max )
11
+ static inline int maximum ( int a , int b )
12
12
{
13
- int left_max = 0 ;
14
- int right_max = 0 ;
13
+ return a > b ? a : b ;
14
+ }
15
15
16
- if (node -> left != NULL ) {
17
- left_max = partition (node -> left , max );
16
+ static int dfs (struct TreeNode * root , int * max )
17
+ {
18
+ if (root == NULL ) {
19
+ return 0 ;
18
20
}
19
21
20
- if ( node -> right != NULL ) {
21
- right_max = partition ( node -> right , max );
22
- }
22
+ /* In case of negative node value */
23
+ int l = maximum ( dfs ( root -> left , max ), 0 );
24
+ int r = maximum ( dfs ( root -> right , max ), 0 );
23
25
24
- int sum = node -> val + left_max + right_max ;
26
+ int sum = root -> val + l + r ;
25
27
if (sum > * max ) {
26
28
* max = sum ;
27
29
}
28
30
29
- return node -> val + (right_max > left_max ? right_max : left_max );
31
+ /* The return value does not equal the sum value
32
+ * since we need to return path through the root node
33
+ */
34
+ return root -> val + maximum (l , r );
30
35
}
31
36
32
37
static int maxPathSum (struct TreeNode * root )
33
38
{
34
- if (root == NULL ) {
35
- return 0 ;
36
- }
37
-
38
39
int max = INT_MIN ;
39
- partition (root , & max );
40
+ dfs (root , & max );
40
41
return max ;
41
42
}
42
43
You can’t perform that action at this time.
0 commit comments