diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 132469e0..a574736e 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -46,6 +46,7 @@ | 112 | [Path Sum](https://leetcode.com/problems/path-sum/) | [C](./src/112.c) | Easy | | 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/) | [C](./src/118.c) | Easy | | 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | [C](./src/121.c) | Easy | +| 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/description/) | [C](./src/124.c) | Hard | | 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C](./src/125.c) | Easy | | 136 | [Single Number](https://leetcode.com/problems/single-number/) | [C](./src/136.c) | Easy | | 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | [C](./src/141.c) | Easy | diff --git a/leetcode/src/124.c b/leetcode/src/124.c new file mode 100644 index 00000000..a846dfcb --- /dev/null +++ b/leetcode/src/124.c @@ -0,0 +1,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; +}