From 403aeabbe723ed86527511ed0562abda7d2538be Mon Sep 17 00:00:00 2001 From: anshupatel06 <72225878+anshupatel06@users.noreply.github.com> Date: Fri, 2 Oct 2020 13:13:39 +0530 Subject: [PATCH] Add files via upload --- maximum path sum in a binary tree.cpp | 67 +++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 maximum path sum in a binary tree.cpp diff --git a/maximum path sum in a binary tree.cpp b/maximum path sum in a binary tree.cpp new file mode 100644 index 0000000..e6be67d --- /dev/null +++ b/maximum path sum in a binary tree.cpp @@ -0,0 +1,67 @@ + +#include +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; +} \ No newline at end of file