Find the maximum sum leaf to root path in a Binary Tree
Last Updated : 23 Jul, 2025
Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root.
Example :
Input:
Output: 60 Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 and the path for maximum is 20->30->10.
[Naive Approach] By Checking Every Path - O(n * h) Time and O(n) Space
The idea is to check of all possible path from root to leaf recursively. So we check for every path that is from root to every leaf and take the sum which path has the maximum sum.
Follow the steps below to solve the problem:
Traverse the binary tree form root to every node and maintain a parent map which contains the parent of a node.
While traversing, if the current node don't has left or right child, then the node is a leaf node.
When we encounter a leaf node, call a separate function which calculates the sum from that leaf to root.
The function calculates the sum by using parent map by recursively calling the function with parent node until we reach root.
Maintain a variable which keeps and updates the maximum sum.
Below is the implementation of the above approach:
C++
// CPP program to find maximum sum leaf to root// path in Binary Tree by checking every path#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Helper function to calculate the sum // from a leaf node to the rootintgetSumOfPath(Node*root,unordered_map<Node*,Node*>&parent){// If the current node has no parent, // return its data (it's the root)if(parent.find(root)==parent.end())returnroot->data;// Recursively sum the current node data// with its parent's path sumreturnroot->data+getSumOfPath(parent[root],parent);}// Function to calculate the maximum leaf-to-root path sumvoidsumCal(Node*root,int&maxx,unordered_map<Node*,Node*>&parent){// Check if the current node is a leaf nodeif(root->left==nullptr&&root->right==nullptr){// Update the maximum sum if the // current path's sum is greatermaxx=max(maxx,getSumOfPath(root,parent));return;}// If the left child exists, set the // current node as its parent and recurseif(root->left){parent[root->left]=root;sumCal(root->left,maxx,parent);}// If the right child exists, set the // current node as its parent and recurseif(root->right){parent[root->right]=root;sumCal(root->right,maxx,parent);}}// Function to return the maximum leaf-// to-root path sum in the binary treeintmaxPathSum(Node*root){// To store each node's parent for path calculationunordered_map<Node*,Node*>parent;// Variable to store the maximum sumintmaxx=0;// Recursively calculate the sum for all pathssumCal(root,maxx,parent);// Return the maximum path sum foundreturnmaxx;}intmain(){// Constructing tree given// 10// / \ // -2 7// / \ // 8 -4Node*root=newNode(10);root->left=newNode(-2);root->right=newNode(7);root->left->left=newNode(8);root->left->right=newNode(-4);intsum=maxPathSum(root);cout<<sum<<endl;return0;}
Java
// Java program to find maximum sum leaf to root// path in Binary Tree by checking every pathimportjava.util.HashMap;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Helper function to calculate the sum// from a leaf node to the rootstaticintgetSumOfPath(Noderoot,HashMap<Node,Node>parent){// If the current node has no parent,// return its data (it's the root)if(!parent.containsKey(root))returnroot.data;// Recursively sum the current node data// with its parent's path sumreturnroot.data+getSumOfPath(parent.get(root),parent);}// Function to calculate the maximum leaf-to-root path sumstaticvoidsumCal(Noderoot,int[]maxx,HashMap<Node,Node>parent){// Check if the current node is a leaf nodeif(root.left==null&&root.right==null){// Update the maximum sum if the// current path's sum is greatermaxx[0]=Math.max(maxx[0],getSumOfPath(root,parent));return;}// If the left child exists, set the// current node as its parent and recurseif(root.left!=null){parent.put(root.left,root);sumCal(root.left,maxx,parent);}// If the right child exists, set the// current node as its parent and recurseif(root.right!=null){parent.put(root.right,root);sumCal(root.right,maxx,parent);}}// Function to return the maximum leaf-to-root // path sum in the binary treestaticintmaxPathSum(Noderoot){// To store each node's parent for path calculationHashMap<Node,Node>parent=newHashMap<>();// Variable to store the maximum sumint[]maxx={0};// Recursively calculate the sum for all pathssumCal(root,maxx,parent);// Return the maximum path sum foundreturnmaxx[0];}publicstaticvoidmain(String[]args){// Constructing tree given// 10// / \// -2 7// / \// 8 -4Noderoot=newNode(10);root.left=newNode(-2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(-4);intsum=maxPathSum(root);System.out.println(sum);}}
Python
# Python program to find maximum sum leaf to root# path in Binary Tree by checking every pathclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Helper function to calculate the sum# from a leaf node to the rootdefget_sum_of_path(root,parent):# If the current node has no parent,# return its data (it's the root)ifrootnotinparent:returnroot.data# Recursively sum the current node data# with its parent's path sumreturnroot.data+get_sum_of_path(parent[root],parent)# Function to calculate the maximum leaf-to-root path sumdefsum_cal(root,maxx,parent):# Check if the current node is a leaf nodeifroot.leftisNoneandroot.rightisNone:# Update the maximum sum if the# current path's sum is greatermaxx[0]=max(maxx[0],get_sum_of_path(root,parent))return# If the left child exists, set the# current node as its parent and recurseifroot.left:parent[root.left]=rootsum_cal(root.left,maxx,parent)# If the right child exists, set the# current node as its parent and recurseifroot.right:parent[root.right]=rootsum_cal(root.right,maxx,parent)# Function to return the maximum leaf-to-root path # sum in the binary treedefmax_path_sum(root):# To store each node's parent for # path calculationparent={}# Variable to store the maximum summaxx=[0]# Recursively calculate the sum for all pathssum_cal(root,maxx,parent)# Return the maximum path sum foundreturnmaxx[0]if__name__=="__main__":# Constructing tree given# 10# / \# -2 7# / \# 8 -4root=Node(10)root.left=Node(-2)root.right=Node(7)root.left.left=Node(8)root.left.right=Node(-4)sum_result=max_path_sum(root)print(sum_result)
C#
// C# program to find maximum sum leaf to root// path in Binary Tree by checking every pathusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Helper function to calculate the sum// from a leaf node to the rootstaticintgetSumOfPath(Noderoot,Dictionary<Node,Node>parent){// If the current node has no parent,// return its data (it's the root)if(!parent.ContainsKey(root))returnroot.data;// Recursively sum the current node data// with its parent's path sumreturnroot.data+getSumOfPath(parent[root],parent);}// Function to calculate the maximum leaf-to-root path sumstaticvoidsumCal(Noderoot,refintmaxx,Dictionary<Node,Node>parent){// Check if the current node is a leaf nodeif(root.left==null&&root.right==null){// Update the maximum sum if the// current path's sum is greatermaxx=Math.Max(maxx,getSumOfPath(root,parent));return;}// If the left child exists, set the// current node as its parent and recurseif(root.left!=null){parent[root.left]=root;sumCal(root.left,refmaxx,parent);}// If the right child exists, set the// current node as its parent and recurseif(root.right!=null){parent[root.right]=root;sumCal(root.right,refmaxx,parent);}}// Function to return the maximum leaf-to-root // path sum in the binary treestaticintmaxPathSum(Noderoot){// To store each node's parent for path calculationDictionary<Node,Node>parent=newDictionary<Node,Node>();// Variable to store the maximum sumintmaxx=0;// Recursively calculate the sum for all pathssumCal(root,refmaxx,parent);// Return the maximum path sum foundreturnmaxx;}staticvoidMain(string[]args){// Constructing tree given// 10// / \// -2 7// / \// 8 -4Noderoot=newNode(10);root.left=newNode(-2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(-4);intsum=maxPathSum(root);Console.WriteLine(sum);}}
JavaScript
// JavaScript program to find maximum sum leaf to root// path in Binary Tree by checking every pathclassNode{constructor(x){this.data=x;this.left=this.right=null;}}// Helper function to calculate the sum// from a leaf node to the rootfunctiongetSumOfPath(root,parent){// If the current node has no parent,// return its data (it's the root)if(!parent.has(root))returnroot.data;// Recursively sum the current node data// with its parent's path sumreturnroot.data+getSumOfPath(parent.get(root),parent);}// Function to calculate the maximum leaf-to-root path sumfunctionsumCal(root,maxx,parent){// Check if the current node is a leaf nodeif(root.left===null&&root.right===null){// Update the maximum sum if the// current path's sum is greatermaxx[0]=Math.max(maxx[0],getSumOfPath(root,parent));return;}// If the left child exists, set the// current node as its parent and recurseif(root.left!==null){parent.set(root.left,root);sumCal(root.left,maxx,parent);}// If the right child exists, set the// current node as its parent and recurseif(root.right!==null){parent.set(root.right,root);sumCal(root.right,maxx,parent);}}// Function to return the maximum leaf-to-root path // sum in the binary treefunctionmaxPathSum(root){// To store each node's parent for path calculationletparent=newMap();// Variable to store the maximum sumletmaxx=[0];// Recursively calculate the sum for all pathssumCal(root,maxx,parent);// Return the maximum path sum foundreturnmaxx[0];}// Constructing tree given// 10// / \// -2 7// / \// 8 -4letroot=newNode(10);root.left=newNode(-2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(-4);letsum=maxPathSum(root);console.log(sum);
Output
17
Time Complexity: O(n * h) Where n is number of nodes in tree and h is height of tree. Auxiliary Space: O(n)
[Expected Approach] By Keeping Track of Maximum Sum - O(n) Time and O(n) Space
The idea is to keep track of current sum and maximum sum while traversing the tree and update maximum sum if at leaf node current sum is greater them maximum sum.
Follow the steps below to solve the problem:
If the node is the root, return its data.
If the node is a leaf, Check where current sum is greater than maximum sum, then update maximum sum.
For non-leaf nodes, update current sum and make recursive call on both left and right child.
Below is the implementation of the above approach:
C++
// CPP program to find maximum sum leaf to root// path in Binary Tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Helper function to find the leaf node that contributes// to the maximum sum and returns the maximum sum from the// root to that leafvoidfindMaxSum(Node*root,intcurrSum,int&mxSum){if(root==nullptr)return;// Add the current node's data to the path sumcurrSum+=root->data;// Check if this node is a leaf nodeif(root->left==nullptr&&root->right==nullptr){// Update the maximum sum and target // leaf if a higher sum is foundif(currSum>mxSum){mxSum=currSum;}}// Recursively check for the maximum sum // in the left and right subtreesfindMaxSum(root->left,currSum,mxSum);findMaxSum(root->right,currSum,mxSum);}// Function to return the maximum sum// path from root to leafintmaxPathSum(Node*root){// empty tree has sum 0if(root==nullptr)return0;// Initialize max sum as the smallest possible integerintmxSum=INT_MIN;// Find the target leaf and maximum sumfindMaxSum(root,0,mxSum);// Return the maximum sum foundreturnmxSum;}intmain(){// Constructing tree:// 10// / \ // -2 7// / \ // 8 -4Node*root=newNode(10);root->left=newNode(-2);root->right=newNode(7);root->left->left=newNode(8);root->left->right=newNode(-4);intsum=maxPathSum(root);cout<<sum<<endl;return0;}
C
// C program to find maximum sum leaf to// root path in Binary Tree#include<stdio.h>#include<stdlib.h>#include<limits.h>structNode{intdata;structNode*left;structNode*right;};// Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the// root to that leafvoidfindMaxSum(structNode*root,intcurrSum,int*mxSum){if(root==NULL)return;// Add the current node's data to the path sumcurrSum+=root->data;// Check if this node is a leaf nodeif(root->left==NULL&&root->right==NULL){// Update the maximum sum if a higher sum is foundif(currSum>*mxSum){*mxSum=currSum;}}// Recursively check for the maximum // sum in the left and right subtreesfindMaxSum(root->left,currSum,mxSum);findMaxSum(root->right,currSum,mxSum);}// Function to return the maximum sum path from root to leafintmaxPathSum(structNode*root){// Empty tree has sum 0if(root==NULL)return0;// Initialize max sum as the smallest possible integerintmxSum=INT_MIN;// Find the target leaf and maximum sumfindMaxSum(root,0,&mxSum);// Return the maximum sum foundreturnmxSum;}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->left=newNode->right=NULL;returnnewNode;}intmain(){// Constructing tree:// 10// / \ // -2 7// / \ // 8 -4structNode*root=createNode(10);root->left=createNode(-2);root->right=createNode(7);root->left->left=createNode(8);root->left->right=createNode(-4);intsum=maxPathSum(root);printf("%d\n",sum);return0;}
Java
// Java program to find maximum sum leaf to // root path in Binary TreeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the// root to that leafstaticvoidfindMaxSum(Noderoot,intcurrSum,int[]mxSum){if(root==null)return;// Add the current node's data to the path sumcurrSum+=root.data;// Check if this node is a leaf nodeif(root.left==null&&root.right==null){// Update the maximum sum if a higher sum is foundif(currSum>mxSum[0]){mxSum[0]=currSum;}}// Recursively check for the maximum sum // in the left and right subtreesfindMaxSum(root.left,currSum,mxSum);findMaxSum(root.right,currSum,mxSum);}// Function to return the maximum sum path from root to leafstaticintmaxPathSum(Noderoot){// Empty tree has sum 0if(root==null)return0;// Initialize max sum as the smallest possible integerint[]mxSum={Integer.MIN_VALUE};// Find the target leaf and maximum sumfindMaxSum(root,0,mxSum);// Return the maximum sum foundreturnmxSum[0];}publicstaticvoidmain(String[]args){// Constructing tree:// 10// / \// -2 7// / \// 8 -4Noderoot=newNode(10);root.left=newNode(-2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(-4);intsum=maxPathSum(root);System.out.println(sum);}}
Python
# Python program to find maximum sum leaf # to root path in Binary TreeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Helper function to find the leaf node that contributes # to the maximum sum and returns the maximum sum from the # root to that leafdeffindMaxSum(root,currSum,mxSum):ifrootisNone:return# Add the current node's data to the path sumcurrSum+=root.data# Check if this node is a leaf nodeifroot.leftisNoneandroot.rightisNone:# Update the maximum sum if a higher sum is foundifcurrSum>mxSum[0]:mxSum[0]=currSum# Recursively check for the maximum sum# in the left and right subtreesfindMaxSum(root.left,currSum,mxSum)findMaxSum(root.right,currSum,mxSum)# Function to return the maximum sum path# from root to leafdefmaxPathSum(root):# Empty tree has sum 0ifrootisNone:return0# Initialize max sum as the smallest possible integermxSum=[-float('inf')]# Find the target leaf and maximum sumfindMaxSum(root,0,mxSum)# Return the maximum sum foundreturnmxSum[0]if__name__=="__main__":# Constructing tree:# 10# / \# -2 7# / \# 8 -4root=Node(10)root.left=Node(-2)root.right=Node(7)root.left.left=Node(8)root.left.right=Node(-4)sum=maxPathSum(root)print(sum)
C#
// C# program to find maximum sum leaf // to root path in Binary TreeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the// root to that leafstaticvoidfindMaxSum(Noderoot,intcurrSum,refintmxSum){if(root==null)return;// Add the current node's data to the path sumcurrSum+=root.data;// Check if this node is a leaf nodeif(root.left==null&&root.right==null){// Update the maximum sum if a higher sum is foundif(currSum>mxSum){mxSum=currSum;}}// Recursively check for the maximum // sum in the left and right subtreesfindMaxSum(root.left,currSum,refmxSum);findMaxSum(root.right,currSum,refmxSum);}// Function to return the maximum sum path from root to leafstaticintmaxPathSum(Noderoot){// Empty tree has sum 0if(root==null)return0;// Initialize max sum as the smallest possible integerintmxSum=int.MinValue;// Find the target leaf and maximum sumfindMaxSum(root,0,refmxSum);// Return the maximum sum foundreturnmxSum;}staticvoidMain(){// Constructing tree:// 10// / \// -2 7// / \// 8 -4Noderoot=newNode(10);root.left=newNode(-2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(-4);intsum=maxPathSum(root);Console.WriteLine(sum);}}
JavaScript
// JavaScript program to find maximum // sum leaf to root path in Binary TreeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Helper function to find the leaf node that contributes // to the maximum sum and returns the maximum sum from the// root to that leaffunctionfindMaxSum(root,currSum,mxSum){if(root===null)return;// Add the current node's data to the path sumcurrSum+=root.data;// Check if this node is a leaf nodeif(root.left===null&&root.right===null){// Update the maximum sum if a higher sum is foundif(currSum>mxSum[0]){mxSum[0]=currSum;}}// Recursively check for the maximum sum // in the left and right subtreesfindMaxSum(root.left,currSum,mxSum);findMaxSum(root.right,currSum,mxSum);}// Function to return the maximum sum path from// root to leaffunctionmaxPathSum(root){// Empty tree has sum 0if(root===null)return0;// Initialize max sum as the smallest possible integerletmxSum=[-Infinity];// Find the target leaf and maximum sumfindMaxSum(root,0,mxSum);// Return the maximum sum foundreturnmxSum[0];}// Constructing tree:// 10// / \// -2 7// / \// 8 -4letroot=newNode(10);root.left=newNode(-2);root.right=newNode(7);root.left.left=newNode(8);root.left.right=newNode(-4);letsum=maxPathSum(root);console.log(sum);
Output
17
Time Complexity: O(n) Where n is number of nodes in tree. Auxiliary Space: O(n) , Function call stack space.