feat: add Binary Tree Maximum Path Sum (#1179)

* add leetcode Binary Tree Maximum Path Sum

* Update leetcode/src/124.c

Co-authored-by: Taj <tjgurwara99@users.noreply.github.com>

Co-authored-by: David Leal <halfpacho@gmail.com>
Co-authored-by: Taj <tjgurwara99@users.noreply.github.com>
This commit is contained in:
Alexander Pantyukhin 2023-01-22 04:42:07 +04:00 committed by GitHub
parent 5ac30afa86
commit 74ef8f5806
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 0 deletions

View File

@ -46,6 +46,7 @@
| 112 | [Path Sum](https://leetcode.com/problems/path-sum/) | [C](./src/112.c) | Easy | | 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 | | 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 | | 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 | | 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 | | 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 | | 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | [C](./src/141.c) | Easy |

36
leetcode/src/124.c Normal file
View File

@ -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;
}