Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a problem Maximum path sum from any node #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions Medium/Maximum path sum from any node.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree.

Example 1:

Input:
10
/ \
2 -25
/ \ / \
20 1 3 4
Output: 32
Explanation: Path in the given tree goes
like 10 , 2 , 20 which gives the max
sum as 32.
Example 2:

Input:
10
/ \
2 5
\
-2
Output: 17
Explanation: Path in the given tree goes
like 2 , 10 , 5 which gives the max sum
as 17.
*/

#include<bits/stdc++.h>
using namespace std;

// A binary tree node
struct Node
{
int data;
struct Node* left, *right;
};

// A utility function to allocate a new node
struct Node* newNode(int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}

// This function returns overall maximum path sum in 'res'
// And returns max path sum going through root.
int findMaxUtil(Node* root, int &res)
{
//Base Case
if (root == NULL)
return 0;

// l and r store maximum path sum going through left and
// right child of root respectively
int l = findMaxUtil(root->left,res);
int r = findMaxUtil(root->right,res);

// Max path for parent call of root. This path must
// include at-most one child of root
int max_single = max(max(l, r) + root->data, root->data);

// Max Top represents the sum when the Node under
// consideration is the root of the maxsum path and no
// ancestors of root are there in max sum path
int max_top = max(max_single, l + r + root->data);

res = max(res, max_top); // Store the Maximum Result.

return max_single;
}

// Returns maximum path sum in tree with given root
int findMaxSum(Node *root)
{
// Initialize result
int res = INT_MIN;

// Compute and return result
findMaxUtil(root, res);
return res;
}

// Driver program
int main(void)
{
struct Node *root = newNode(10);
root->left = newNode(2);
root->right = newNode(10);
root->left->left = newNode(20);
root->left->right = newNode(1);
root->right->right = newNode(-25);
root->right->right->left = newNode(3);
root->right->right->right = newNode(4);
cout << "Max path sum is " << findMaxSum(root);
return 0;
}