From 86603748ea127179daa64f46c6b4f48d4df5ca40 Mon Sep 17 00:00:00 2001 From: Manu Gupta Date: Fri, 2 Oct 2020 00:43:58 +0530 Subject: [PATCH] Added a problem Maximum path sum from any node --- Medium/Maximum path sum from any node.cpp | 99 +++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Medium/Maximum path sum from any node.cpp diff --git a/Medium/Maximum path sum from any node.cpp b/Medium/Maximum path sum from any node.cpp new file mode 100644 index 0000000..14680b4 --- /dev/null +++ b/Medium/Maximum path sum from any node.cpp @@ -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 +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; +}