Skip to content

Commit 82870a0

Browse files
Refine
Signed-off-by: begeekmyfriend <[email protected]>
1 parent 4d550a5 commit 82870a0

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

124_binary_tree_maximum_path_sum/bst_max_path.c

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,35 +8,36 @@ struct TreeNode {
88
struct TreeNode *right;
99
};
1010

11-
static int partition(struct TreeNode *node, int *max)
11+
static inline int maximum(int a, int b)
1212
{
13-
int left_max = 0;
14-
int right_max = 0;
13+
return a > b ? a : b;
14+
}
1515

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;
1820
}
1921

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);
2325

24-
int sum = node->val + left_max + right_max;
26+
int sum = root->val + l + r;
2527
if (sum > *max) {
2628
*max = sum;
2729
}
2830

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);
3035
}
3136

3237
static int maxPathSum(struct TreeNode* root)
3338
{
34-
if (root == NULL) {
35-
return 0;
36-
}
37-
3839
int max = INT_MIN;
39-
partition(root, &max);
40+
dfs(root, &max);
4041
return max;
4142
}
4243

0 commit comments

Comments
 (0)