-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy path124.c
36 lines (30 loc) · 979 Bytes
/
124.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define max(a,b) (((a)>(b))?(a):(b))
int recursiveSolve(struct TreeNode* node, int* result){
if (node == NULL){
return 0;
}
int leftSum = max(recursiveSolve(node->left, result), 0);
int rightSum = max(recursiveSolve(node->right, result), 0);
// Check if it's possible to make a maximum path from left right and current node
int maxValueNode = node->val + leftSum + rightSum;
*result = max(maxValueNode, *result);
// Choose the max sum val path
return node->val + max(leftSum, rightSum);
}
// Depth First Search
// Runtime: O(n), n - the number of nodes in tree.
// Space: O(1)
int maxPathSum(struct TreeNode* root){
const int LOWER_BOUND = -2147483648
int result = LOWER_BOUND;
recursiveSolve(root, &result);
return result;
}