https://www.geeksforgeeks.org/batch/gfg-160-problems/track/tree-gfg-160/problem/maximum-path-sum-from-any-node
class Solution {
public:
// Function to return maximum path sum from any node in a tree.
int findMaxSum(Node *root) {
if(!root) return 0;
maxsum = INT_MIN;
helper(root);
return maxsum;
}
private:
int maxsum;
int helper(Node* root){
if(!root) return 0;
int left = max( 0 , helper(root->left));
int right = max(0 , helper(root->right));
maxsum = max(maxsum , root->data + left +right);
return root->data + max(left ,right);
}
};
Problem Here
Explaination Here
https://www.youtube.com/watch?v=WszrfSwMz58
This code finds the maximum sum of any path in a binary tree. A path can start and end at any nodes and doesn't have to go through the root.
findMaxSum()
cpp
`int findMaxSum(Node *root) { if(!root) return 0;
maxsum = INT_MIN;
helper(root);
return maxsum;
}`
maxsum = INT_MIN
to handle trees with all negative valueshelper()
This is where the main logic happens:
cpp