Given root of a Binary tree, find the maximum sum path from any leaf node to the root.
Example :
Input: root[] = [1, 2, 3, 4, 5, N, 8, N, 2, N, N, 6, 7]
Output: 19 Explanation: There are 4 leaf nodes in the tree, resulting in 4 leaf-to-root paths: 2 -> 4 -> 2 -> 1, 5 -> 2 -> 1, 6 -> 8 -> 3 -> 1, and 7 -> 8 -> 3 -> 1. Among these, the path 7 -> 8 -> 3 -> 1 has the maximum sum. The sum of this path is 7 + 8 + 3 + 1 = 19.
Input: root[] = [1, -2, 3, N, 5, N, 8]
Output: 12 Explanation: There are 2 leaf nodes in the tree, resulting in 2 leaf-to-root paths: 5 -> -2 -> 1 and 8 -> 3 -> 1. Among these, the path 8 -> 3 -> 1 has the maximum sum. The sum of this path is 8 + 3 + 1 = 12.
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 from 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.
C++
#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=INT_MIN;// Recursively calculate the sum for all pathssumCal(root,maxx,parent);// Return the maximum path sum foundreturnmaxx;}// Driver Codeintmain(){// Constructing tree// 1// / \ // 2 3// / \ \ // 4 5 8// \ / \ // 2 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->left->left->right=newNode(2);root->right->right=newNode(8);root->right->right->left=newNode(6);root->right->right->right=newNode(7);intsum=maxPathSum(root);cout<<sum<<endl;return0;}
Java
importjava.util.HashMap;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassGfG{// Helper function to calculate the sum// from a leaf node to the rootpublicstaticintgetSumOfPath(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// sumpublicstaticvoidsumCal(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 treepublicstaticintmaxPathSum(Noderoot){// To store each node's parent for path calculationHashMap<Node,Node>parent=newHashMap<>();// Variable to store the maximum sumint[]maxx={Integer.MIN_VALUE};// Recursively calculate the sum for all pathssumCal(root,maxx,parent);// Return the maximum path sum foundreturnmaxx[0];}// Driver Codepublicstaticvoidmain(String[]args){// Constructing tree// 1// / \// 2 3// / \ \// 4 5 8// \ / \\// 2 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.left.left.right=newNode(2);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);intsum=maxPathSum(root);System.out.println(sum);}}
Python
fromcollectionsimportdefaultdictclassNode: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 treedefmaxPathSum(root):# To store each node's parent for path calculationparent=defaultdict(None)# Variable to store the maximum summaxx=[float('-inf')]# Recursively calculate the sum for all pathssum_cal(root,maxx,parent)# Return the maximum path sum foundreturnmaxx[0]# Driver Codeif__name__=='__main__':# Constructing tree# 1# / \# 2 3# / \ \# 4 5 8# \ / \\# 2 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.left.left.right=Node(2)root.right.right=Node(8)root.right.right.left=Node(6)root.right.right.right=Node(7)sum=maxPathSum(root)print(sum)
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassGfG{// Helper function to calculate the sum// from a leaf node to the rootpublicstaticintgetSumOfPath(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// sumpublicstaticvoidsumCal(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 treepublicstaticintmaxPathSum(Noderoot){// To store each node's parent for path calculationDictionary<Node,Node>parent=newDictionary<Node,Node>();// Variable to store the maximum sumintmaxx=int.MinValue;// Recursively calculate the sum for all pathssumCal(root,refmaxx,parent);// Return the maximum path sum foundreturnmaxx;}// Driver CodepublicstaticvoidMain(){// Constructing tree// 1// / \// 2 3// / \ \// 4 5 8// \ / \// 2 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.left.left.right=newNode(2);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);intsum=maxPathSum(root);Console.WriteLine(sum);}}
JavaScript
// Node classclassNode{constructor(x){this.data=x;this.left=null;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&&!root.right){// Update the maximum sum if the// current path's sum is greatermaxx.val=Math.max(maxx.val,getSumOfPath(root,parent));return;}// If the left child exists, set the// current node as its parent and recurseif(root.left){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){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={val:Number.MIN_SAFE_INTEGER};// Recursively calculate the sum for all pathssumCal(root,maxx,parent);// Return the maximum path sum foundreturnmaxx.val;}// Driver Code// Constructing tree// 1// / \// 2 3// / \ \// 4 5 8// \ / \// 2 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.left.left.right=newNode(2);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);letsum=maxPathSum(root);console.log(sum);
Output
19
Time Complexity: O(n * h) Where n is number of nodes in tree and h is height of tree. Auxiliary Space: O(n)
Keeping Track of Maximum Sum - O(n) Time and O(h) 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.
C++
#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;}// Driver Codeintmain(){// Constructing tree// 1// / \ // 2 3// / \ \ // 4 5 8// \ / \ // 2 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->left->left->right=newNode(2);root->right->right=newNode(8);root->right->right->left=newNode(6);root->right->right->right=newNode(7);intsum=maxPathSum(root);cout<<sum<<endl;return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;publicNode(intitem){data=item;left=right=null;}}publicclassGfG{// Helper function to find the leaf node that// contributes to the maximum sum and returns the// maximum sum from the root to that leafvoidfindMaxSum(Nodenode,intcurrSum,int[]maxSum){if(node==null)return;// Add the current node's data to the path sumcurrSum+=node.data;// Check if this node is a leaf nodeif(node.left==null&&node.right==null){// Update the maximum sum and target// leaf if a higher sum is foundif(currSum>maxSum[0]){maxSum[0]=currSum;}}// Recursively check for the maximum sum// in the left and right subtreesfindMaxSum(node.left,currSum,maxSum);findMaxSum(node.right,currSum,maxSum);}// Function to return the maximum sum// path from root to leafintmaxPathSum(Nodenode){// empty tree has sum 0if(node==null)return0;// Initialize max sum as the smallest possible// integerint[]maxSum={Integer.MIN_VALUE};// Find the target leaf and maximum sumfindMaxSum(node,0,maxSum);// Return the maximum sum foundreturnmaxSum[0];}publicstaticvoidmain(String[]args){GfGtree=newGfG();// Constructing tree// 1// / \// 2 3// / \ \// 4 5 8// \ / \// 2 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.left.left.right=newNode(2);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);intsum=tree.maxPathSum(root);System.out.println(sum);}}
Python
classNode:def__init__(self,data):self.data=dataself.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 and target# leaf 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]# Driver Codeif__name__=='__main__':# Constructing tree# 1# / \# 2 3# / \ \# 4 5 8# \ / \\# 2 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.left.left.right=Node(2)root.right.right=Node(8)root.right.right.left=Node(6)root.right.right.right=Node(7)sum=maxPathSum(root)print(sum)
C#
usingSystem;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassGfG{// 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 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,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;}// Driver CodepublicstaticvoidMain(){// Constructing tree// 1// / \// 2 3// / \ \// 4 5 8// \ / \\// 2 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.left.left.right=newNode(2);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);intsum=maxPathSum(root);Console.WriteLine(sum);}}
JavaScript
// 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 and target// leaf if a higher sum is foundif(currSum>mxSum)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=[Number.NEGATIVE_INFINITY];// Find the target leaf and maximum sumfindMaxSum(root,0,mxSum);// Return the maximum sum foundreturnmxSum[0];}// Driver Code// Constructing tree// 1// / \// 2 3// / \ \// 4 5 8// \ / \\// 2 6 7classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.left.left.right=newNode(2);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);letsum=maxPathSum(root);console.log(sum);
Output
19
Time Complexity: O(n) Where n is number of nodes in tree. Auxiliary Space: O(h), where h is height of tree.