Skip to content

maximum path sum in a binary tree #65

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

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
67 changes: 67 additions & 0 deletions maximum path sum in a binary tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@

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


struct Node
{
int data;
struct Node* left, *right;
};


struct Node* newNode(int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}


int findMaxUtil(Node* root, int &res)
{

if (root == NULL)
return 0;


int l = findMaxUtil(root->left,res);
int r = findMaxUtil(root->right,res);


int max_single = max(max(l, r) + root->data, root->data);


int max_top = max(max_single, l + r + root->data);

res = max(res, max_top);

return max_single;
}


int findMaxSum(Node *root)
{

int res = INT_MIN;


findMaxUtil(root, res);
return res;
}


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