mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-21 21:11:57 +03:00
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:
parent
5ac30afa86
commit
74ef8f5806
@ -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 |
|
||||
|
36
leetcode/src/124.c
Normal file
36
leetcode/src/124.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user