Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another.
Examples:
Input:
Output: 27 Explanation: The maximum sum path may or may not go through the root. For example, in the following binary tree, the maximum sum is 27 (3 + 6 + 9 + 0 - 1 + 10).
To find the maximum path sum between two leaf nodes in a binary tree, traverse each node and recursively calculate the maximum sum from leaf to root in the left subtree of x (Find the maximum sum leaf to root path in a Binary Tree). Find the maximum sum from leaf to root in the right subtree of x. Add the above two calculated values and x->data compare the sum with the maximum value obtained so far and update the maximum value. Return the overall maximum value. The time complexity of the above solution is O(n2).
Approach:
We can find the maximum sum using single traversal of binary tree. The idea is to maintain two values in recursive calls. For every visited node x, we find the maximum root to leaf sum in left and right subtrees of x. We add the two values with x->data, and compare the sum with maximum path sum found so far.
Below is the implementation of above approach:
C++
// C++ program to find maximum path //sum between two leaves of a binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// mxPathSum function to calculate maximum path sum // between two leaves and maximum sum from node to leaf// in a single traversalintmxPathSum(Node*root,int&maxPathSum){// Base case: If the node is null, // return 0if(root==nullptr){return0;}// Recursively calculate the maximum sum from // node to leaf for left and right subtreesintmxLeft=mxPathSum(root->left,maxPathSum);intmxRight=mxPathSum(root->right,maxPathSum);// If both left and right children exist, // update maxPathSumif(root->left!=nullptr&&root->right!=nullptr){// This is the sum of the left path, // right path, and the node's dataintmaxSumPathViaNode=mxLeft+mxRight+root->data;// Update the maximum sum path between// two leavesmaxPathSum=max(maxPathSum,maxSumPathViaNode);// Return the maximum sum from the current // node to a leafreturnroot->data+max(mxLeft,mxRight);}// If only one child exists, return the sum // from the node to leafreturnroot->data+(root->left?mxLeft:mxRight);}// Function to return the maximum path // sum between any two leaves in the binary treeintfindMaxSum(Node*root){// Edge case: If the tree is empty, // return 0if(root==nullptr){return0;}intmaxPathSum=INT_MIN;// Call the helper function to// compute the resultmxPathSum(root,maxPathSum);returnmaxPathSum;}intmain(){// Construct a sample binary tree//// 1// / \ // -2 3// / \ / \ // 8 -1 4 -5Node*root=newNode(1);root->left=newNode(-2);root->right=newNode(3);root->left->left=newNode(8);root->left->right=newNode(-1);root->right->left=newNode(4);root->right->right=newNode(-5);intresult=findMaxSum(root);cout<<result<<endl;return0;}
C
// C++ program to find maximum path //sum between two leaves of a binary tree#include<stdio.h>#include<stdlib.h>#include<limits.h>structNode{intdata;structNode*left,*right;};// mxPathSum function to calculate maximum path// sum between two leaves and maximum sum from node // to leaf in a single traversalintmxPathSum(structNode*root,int*maxPathSum){// Base case: If the node is null, // return 0if(root==NULL){return0;}// Recursively calculate the maximum sum // from node to leaf for left and right subtreesintmxLeft=mxPathSum(root->left,maxPathSum);intmxRight=mxPathSum(root->right,maxPathSum);// If both left and right children exist, // update maxPathSumif(root->left!=NULL&&root->right!=NULL){// This is the sum of the left path,// right path, and the node's dataintmaxSumPathViaNode=mxLeft+mxRight+root->data;// Update the maximum sum path between two leavesif(maxSumPathViaNode>*maxPathSum){*maxPathSum=maxSumPathViaNode;}// Return the maximum sum from the current // node to a leafreturnroot->data+(mxLeft>mxRight?mxLeft:mxRight);}// If only one child exists, return the sum// from the node to leafreturnroot->data+(root->left?mxLeft:mxRight);}// Function to return the maximum path // sum between any two leaves in the binary treeintfindMaxSum(structNode*root){// Edge case: If the tree is empty,// return 0if(root==NULL){return0;}intmaxPathSum=INT_MIN;// Call the helper function to compute// the resultmxPathSum(root,&maxPathSum);returnmaxPathSum;}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=newNode->right=NULL;returnnewNode;}intmain(){// Construct a sample binary tree//// 1// / \ // -2 3// / \ / \ // 8 -1 4 -5structNode*root=createNode(1);root->left=createNode(-2);root->right=createNode(3);root->left->left=createNode(8);root->left->right=createNode(-1);root->right->left=createNode(4);root->right->right=createNode(-5);intresult=findMaxSum(root);printf("%d\n",result);return0;}
Java
// Java program to find maximum path // sum between two leaves of a binary treeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// mxPathSum function to calculate maximum path sum // between two leaves and maximum sum from node to // leaf in a single traversalstaticintmxPathSum(Noderoot,int[]maxPathSum){// Base case: If the node is null, return 0if(root==null){return0;}// Recursively calculate the maximum sum from // node to leaf for left and right subtreesintmxLeft=mxPathSum(root.left,maxPathSum);intmxRight=mxPathSum(root.right,maxPathSum);// If both left and right children exist,// update maxPathSumif(root.left!=null&&root.right!=null){// This is the sum of the left path, // right path, and the node's dataintmaxSumPathViaNode=mxLeft+mxRight+root.data;// Update the maximum sum path between// two leavesmaxPathSum[0]=Math.max(maxPathSum[0],maxSumPathViaNode);// Return the maximum sum from the current// node to a leafreturnroot.data+Math.max(mxLeft,mxRight);}// If only one child exists, return the sum// from the node to leafreturnroot.data+(root.left!=null?mxLeft:mxRight);}// Function to return the maximum path // sum between any two leaves in the binary treestaticintfindMaxSum(Noderoot){// Edge case: If the tree is empty, return 0if(root==null){return0;}int[]maxPathSum=newint[]{Integer.MIN_VALUE};mxPathSum(root,maxPathSum);returnmaxPathSum[0];}publicstaticvoidmain(String[]args){// Construct a sample binary tree//// 1// / \// -2 3// / \ / \// 8 -1 4 -5Noderoot=newNode(1);root.left=newNode(-2);root.right=newNode(3);root.left.left=newNode(8);root.left.right=newNode(-1);root.right.left=newNode(4);root.right.right=newNode(-5);intresult=findMaxSum(root);System.out.println(result);}}
Python
# Python program to find maximum path # sum between two leaves of a binary treeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefmxPathSum(root):globalmaxPathSum# Base case: If the node is null, return 0ifrootisNone:return0# Recursively calculate the maximum sum from # node to leaf for left and right subtreesmxLeft=mxPathSum(root.left)mxRight=mxPathSum(root.right)# If both left and right children exist, # update maxPathSumifroot.leftisnotNoneandroot.rightisnotNone:# This is the sum of the left path, # right path, and the node's datamaxSumPathViaNode=mxLeft+mxRight+root.data# Update the maximum sum path between# two leavesmaxPathSum=max(maxPathSum,maxSumPathViaNode)# Return the maximum sum from the current node # to a leafreturnroot.data+max(mxLeft,mxRight)# If only one child exists, return the sum from the# node to leafreturnroot.data+(mxLeftifroot.leftelsemxRight)deffindMaxSum(root):globalmaxPathSum# Edge case: If the tree is empty,# return 0ifrootisNone:return0maxPathSum=float('-inf')mxPathSum(root)returnmaxPathSum# Construct a sample binary tree## 1# / \# -2 3# / \ / \# 8 -1 4 -5root=Node(1)root.left=Node(-2)root.right=Node(3)root.left.left=Node(8)root.left.right=Node(-1)root.right.left=Node(4)root.right.right=Node(-5)result=findMaxSum(root)print(result)
C#
// C# program to find maximum path // sum between two leaves of a binary treeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// mxPathSum function to calculate maximum path sum between two leaves// and maximum sum from node to leaf in a single traversalstaticintmxPathSum(Noderoot,refintmaxPathSum){// Base case: If the node is null, return 0if(root==null){return0;}// Recursively calculate the maximum sum from // node to leaf for left and right subtreesintmxLeft=mxPathSum(root.left,refmaxPathSum);intmxRight=mxPathSum(root.right,refmaxPathSum);// If both left and right children exist, // update maxPathSumif(root.left!=null&&root.right!=null){// This is the sum of the left path, // right path, and the node's dataintmaxSumPathViaNode=mxLeft+mxRight+root.data;// Update the maximum sum path between // two leavesmaxPathSum=Math.Max(maxPathSum,maxSumPathViaNode);// Return the maximum sum from the current // node to a leafreturnroot.data+Math.Max(mxLeft,mxRight);}// If only one child exists, return the sum from// the node to leafreturnroot.data+(root.left!=null?mxLeft:mxRight);}// Function to return the maximum path // sum between any two leaves in the binary treestaticintFindMaxSum(Noderoot){// Edge case: If the tree is empty,// return 0if(root==null){return0;}intmaxPathSum=int.MinValue;// Call the helper function to // compute the resultmxPathSum(root,refmaxPathSum);returnmaxPathSum;}staticvoidMain(string[]args){// Construct a sample binary tree//// 1// / \// -2 3// / \ / \// 8 -1 4 -5Noderoot=newNode(1);root.left=newNode(-2);root.right=newNode(3);root.left.left=newNode(8);root.left.right=newNode(-1);root.right.left=newNode(4);root.right.right=newNode(-5);intresult=FindMaxSum(root);Console.WriteLine(result);}}
JavaScript
// JavaScript program to find maximum path // sum between two leaves of a binary treeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// mxPathSum function to calculate maximum path // sum between two leaves and maximum sum from node// to leaf in a single traversalfunctionmxPathSum(root){if(root===null){return0;}constmxLeft=mxPathSum(root.left);constmxRight=mxPathSum(root.right);// If both left and right children exist, // update maxPathSumif(root.left!==null&&root.right!==null){// This is the sum of the left path, // right path, and the node's dataconstmaxSumPathViaNode=mxLeft+mxRight+root.data;maxPathSum=Math.max(maxPathSum,maxSumPathViaNode);// Return the maximum sum from the current// node to a leafreturnroot.data+Math.max(mxLeft,mxRight);}// If only one child exists, return the sum from // the node to leafreturnroot.data+(root.left?mxLeft:mxRight);}// Function to return the maximum path sum between any // two leaves in the binary treefunctionfindMaxSum(root){maxPathSum=Number.NEGATIVE_INFINITY;mxPathSum(root);returnmaxPathSum;}// Construct a sample binary tree//// 1// / \// -2 3// / \ / \// 8 -1 4 -5constroot=newNode(1);root.left=newNode(-2);root.right=newNode(3);root.left.left=newNode(8);root.left.right=newNode(-1);root.right.left=newNode(4);root.right.right=newNode(-5);constresult=findMaxSum(root);console.log(result);
Output
14
Time complexity: O(n) where n is the number of nodes Auxiliary Space: O(h), where h is height of tree.