Sum of nodes on the longest path from root to leaf node
Last Updated : 19 May, 2025
Given a binary tree containing n nodes. The task is to find the sum of all nodes on the longest path from root to leaf node. If two or more paths compete for the longest path, then the path having the maximum sum of nodes is considered.
The highlighted nodes (4, 2, 3) above are part of the longest root to leaf path having sum = (4 + 2 + 3) = 9
Input: root[] = [4, 2, 5, 7, 1, 2, 3, N, N, 6, N] Output: 13 Explanation: The highlighted nodes (4, 2, 1, 6) above are part of the longest root to leaf path having sum = (4 + 2 + 1 + 6) = 13
[Better Approach] Using level order traversal - O(n) Time and O(n) Space
The idea is to initialize maxSumand maxLento 0, use a queue for level order traversal starting with the root, and while the queue is not empty, dequeue nodes and update maxLenand maxSumfor leaf nodes, and enqueue their children with updated sums and lengths, finally returning maxSum.
C++
// C++ implementation to find the sum of nodes// on the longest path from root to leaf node // using level order traversal#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to calculate the sum of the longest root to // leaf path using level order traversalintsumOfLongRootToLeafPath(Node*root){// Base case: if the tree is emptyif(!root)return0;// Initialize variables to stor// e maximum length and sumintmaxSum=0;intmaxLen=0;// Queue for level order traversal, storing pairs of// nodes and their corresponding sum and lengthqueue<pair<Node*,pair<int,int>>>q;// Starting with the root node, initial// sum, and lengthq.push({root,{root->data,1}});while(!q.empty()){autofront=q.front();q.pop();Node*node=front.first;intsum=front.second.first;intlen=front.second.second;// If it's a leaf node, check if we need// to update maxLen and maxSumif(!node->left&&!node->right){if(len>maxLen){maxLen=len;maxSum=sum;}elseif(len==maxLen&&sum>maxSum){maxSum=sum;}}// Push left and right children // into the queueif(node->left){q.push({node->left,{sum+node->left->data,len+1}});}if(node->right){q.push({node->right,{sum+node->right->data,len+1}});}}returnmaxSum;}intmain(){// binary tree formation// 4// / \ // 2 5// / \ // 1 3Node*root=newNode(4);root->left=newNode(2);root->right=newNode(5);root->left->left=newNode(1);root->left->right=newNode(3);cout<<sumOfLongRootToLeafPath(root);return0;}
Java
// Java implementation to find the sum of nodes// on the longest path from root to leaf node // using level order traversalimportjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to calculate the sum of the longest // root to leaf path using level order traversalstaticintsumOfLongRootToLeafPath(Noderoot){// Base case: if the tree is emptyif(root==null)return0;// Initialize variables to store // maximum length and sumintmaxSum=0;intmaxLen=0;// Queue for level order traversalQueue<Object[]>queue=newLinkedList<>();queue.add(newObject[]{root,root.data,1});while(!queue.isEmpty()){Object[]front=queue.poll();Nodenode=(Node)front[0];intsum=(int)front[1];intlen=(int)front[2];// If it's a leaf node, check if we need to// update maxLen and maxSumif(node.left==null&&node.right==null){if(len>maxLen){maxLen=len;maxSum=sum;}elseif(len==maxLen&&sum>maxSum){maxSum=sum;}}// Push left and right children into the queueif(node.left!=null){queue.add(newObject[]{node.left,sum+node.left.data,len+1});}if(node.right!=null){queue.add(newObject[]{node.right,sum+node.right.data,len+1});}}returnmaxSum;}publicstaticvoidmain(String[]args){// binary tree formation// 4// / \ // 2 5// / \// 1 3Noderoot=newNode(4);root.left=newNode(2);root.right=newNode(5);root.left.left=newNode(1);root.left.right=newNode(3);System.out.println(sumOfLongRootToLeafPath(root));}}
Python
# Python implementation to find the sum of nodes# on the longest path from root to leaf node # using level order traversalclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefsumOfLongRootToLeafPath(root):# Base case: if the tree is emptyifnotroot:return0# Initialize variables to store maximum# length and summaxSum=0maxLen=0# Queue for level order traversalqueue=[(root,root.data,1)]whilequeue:node,sum,length=queue.pop(0)# If it's a leaf node, check if we need to # update maxLen and maxSumifnotnode.leftandnotnode.right:iflength>maxLen:maxLen=lengthmaxSum=sumeliflength==maxLenandsum>maxSum:maxSum=sum# Push left and right children into # the queueifnode.left:queue.append((node.left,sum+node.left.data,length+1))ifnode.right:queue.append((node.right,sum+node.right.data,length+1))returnmaxSumif__name__=="__main__":# binary tree formation# 4# / \ # 2 5# / \ # 1 3root=Node(4)root.left=Node(2)root.right=Node(5)root.left.left=Node(1)root.left.right=Node(3)print(sumOfLongRootToLeafPath(root))
C#
// C# implementation to find the sum of nodes// on the longest path from root to leaf node // using level order traversalusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to calculate the sum of the longest // root to leaf path using level order traversalstaticintsumOfLongRootToLeafPath(Noderoot){// Base case: if the tree is emptyif(root==null)return0;// Initialize variables to store// maximum length and sumintmaxSum=0;intmaxLen=0;// Queue for level order traversalQueue<Tuple<Node,int,int>>queue=newQueue<Tuple<Node,int,int>>();queue.Enqueue(Tuple.Create(root,root.data,1));while(queue.Count>0){varfront=queue.Dequeue();Nodenode=front.Item1;intsum=front.Item2;intlen=front.Item3;// If it's a leaf node, check if we need// to update maxLen and maxSumif(node.left==null&&node.right==null){if(len>maxLen){maxLen=len;maxSum=sum;}elseif(len==maxLen&&sum>maxSum){maxSum=sum;}}// Push left and right children into the queueif(node.left!=null){queue.Enqueue(Tuple.Create(node.left,sum+node.left.data,len+1));}if(node.right!=null){queue.Enqueue(Tuple.Create(node.right,sum+node.right.data,len+1));}}returnmaxSum;}staticvoidMain(){// binary tree formation// 4// / \ // 2 5// / \ // 1 3 Noderoot=newNode(4);root.left=newNode(2);root.right=newNode(5);root.left.left=newNode(1);root.left.right=newNode(3);Console.WriteLine(sumOfLongRootToLeafPath(root));}}
JavaScript
// JavaScript implementation to find the sum of nodes// on the longest path from root to leaf node// using level order traversalclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionsumOfLongRootToLeafPath(root){// Base case: if the tree is emptyif(!root)return0;// Initialize variables to store // maximum length and sumletmaxSum=0;letmaxLen=0;// Queue for level order traversalconstqueue=[[root,root.data,1]];while(queue.length){const[node,sum,length]=queue.shift();// If it's a leaf node, check if we need to // update maxLen and maxSumif(!node.left&&!node.right){if(length>maxLen){maxLen=length;maxSum=sum;}elseif(length===maxLen&&sum>maxSum){maxSum=sum;}}// Push left and right children into the queueif(node.left){queue.push([node.left,sum+node.left.data,length+1]);}if(node.right){queue.push([node.right,sum+node.right.data,length+1]);}}returnmaxSum;}// 4// / \ // 2 5// / \ // 1 3 constroot=newNode(4);root.left=newNode(2);root.right=newNode(5);root.left.left=newNode(1);root.left.right=newNode(3);console.log(sumOfLongRootToLeafPath(root));
Output
9
[Expected Approach] Using Recursive - O(n) Time and O(h) Space
The idea is to initializes two variables to track the maximum path length and sum in a binary tree, recursively traverses the tree, adding node values to a running sum and incrementing the path length. When a null node is reached, function checks if the current path length is greater than the stored maximum. if so, function updates both the length and sum. If the lengths are equal, function updates the sum if the current sum is greater. Finally, function returns the maximum sum of the longest path from the root to a leaf.
Illustration:
C++
// C++ implementation to find the sum of nodes// on the longest path from root to leaf node#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};voidsumOfRootToLeaf(Node*root,intsum,intlen,int&maxLen,int&maxSum){// Base case: if the current node is nullif(!root){// Checking if the current path has a longer length // and update maxLen and maxSum accordinglyif(len>maxLen){maxLen=len;maxSum=sum;}// If the lengths are equal, check if the current sum is // greater and update maxSum if necessaryelseif(len==maxLen&&sum>maxSum){maxSum=sum;}return;}// Recursively calculating the sum of// the left and right subtreessumOfRootToLeaf(root->left,sum+root->data,len+1,maxLen,maxSum);sumOfRootToLeaf(root->right,sum+root->data,len+1,maxLen,maxSum);}// Function to calculate the sum of the longest root to leaf pathintsumOfLongRootToLeafPath(Node*root){// Base case: if the tree is emptyif(!root)return0;// Initializing the variables to store the maximum length and sumintmaxSum=INT_MIN,maxLen=0;// Calling the utility functionsumOfRootToLeaf(root,0,0,maxLen,maxSum);// Returning the maximum sumreturnmaxSum;}intmain(){// binary tree formation// 4// / \ // 2 5// / \ // 1 3 Node*root=newNode(4);root->left=newNode(2);root->right=newNode(5);root->left->left=newNode(1);root->left->right=newNode(3);cout<<sumOfLongRootToLeafPath(root);return0;}
Java
// Java implementation to find the sum of nodes// on the longest path from root to leaf nodeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{staticvoidsumOfRootToLeaf(Noderoot,intsum,intlength,int[]maxLen,int[]maxSum){// Base case: if the current node is nullif(root==null){// Checking if the current path has a longer// length and update maxLen and maxSum// accordinglyif(length>maxLen[0]){maxLen[0]=length;maxSum[0]=sum;}// If the lengths are equal, check if the// current sum is greater and update maxSum if// necessaryelseif(length==maxLen[0]&&sum>maxSum[0]){maxSum[0]=sum;}return;}// Recursively calculating the sum of// the left and right subtreessumOfRootToLeaf(root.left,sum+root.data,length+1,maxLen,maxSum);sumOfRootToLeaf(root.right,sum+root.data,length+1,maxLen,maxSum);}// Function to calculate the sum of the longest root to// leaf pathstaticintsumOfLongRootToLeafPath(Noderoot){// Base case: if the tree is emptyif(root==null)return0;// Initializing the variables to // store the maximum length and sumint[]maxSum={Integer.MIN_VALUE};int[]maxLen={0};// Calling the utility functionsumOfRootToLeaf(root,0,0,maxLen,maxSum);// Returning the maximum sumreturnmaxSum[0];}publicstaticvoidmain(String[]args){// binary tree formation// 4// / \ // 2 5// / \ // 1 3 Noderoot=newNode(4);root.left=newNode(2);root.right=newNode(5);root.left.left=newNode(1);root.left.right=newNode(3);System.out.println(sumOfLongRootToLeafPath(root));}}
Python
# Python implementation to find the sum of nodes# on the longest path from root to leaf nodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefsumOfRootToLeaf(root,sum,length,maxLen,maxSum):# Base case: if the current node is nullifnotroot:# Checking if the current path has a longer length # and update maxLen and maxSum accordinglyiflength>maxLen[0]:maxLen[0]=lengthmaxSum[0]=sum# If the lengths are equal, check if the current sum is # greater and update maxSum if necessaryeliflength==maxLen[0]andsum>maxSum[0]:maxSum[0]=sumreturn# Recursively calculating the sum of# the left and right subtreessumOfRootToLeaf(root.left,sum+root.data,length+1,maxLen,maxSum)sumOfRootToLeaf(root.right,sum+root.data,length+1,maxLen,maxSum)# Function to calculate the sum of the longest root to leaf pathdefsumOfLongRootToLeafPath(root):# Base case: if the tree is emptyifnotroot:return0# Initializing the variables to store# the maximum length and summaxSum=[-float('inf')]maxLen=[0]# Calling the utility functionsumOfRootToLeaf(root,0,0,maxLen,maxSum)# Returning the maximum sumreturnmaxSum[0]if__name__=="__main__":# binary tree formation# 4# / \ # 2 5# / \ # 1 3root=Node(4)root.left=Node(2)root.right=Node(5)root.left.left=Node(1)root.left.right=Node(3)print(sumOfLongRootToLeafPath(root))
C#
// C# implementation to find the sum of nodes// on the longest path from root to leaf nodeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{staticvoidsumOfRootToLeaf(Noderoot,intsum,intlength,refintmaxLen,refintmaxSum){// Base case: if the current node is nullif(root==null){// Checking if the current path has a longer length // and update maxLen and maxSum accordinglyif(length>maxLen){maxLen=length;maxSum=sum;}// If the lengths are equal, check if the current sum is // greater and update maxSum if necessaryelseif(length==maxLen&&sum>maxSum){maxSum=sum;}return;}// Recursively calculating the sum of// the left and right subtreessumOfRootToLeaf(root.left,sum+root.data,length+1,refmaxLen,refmaxSum);sumOfRootToLeaf(root.right,sum+root.data,length+1,refmaxLen,refmaxSum);}// Function to calculate the sum of the longest// root to leaf pathstaticpublicintsumOfLongRootToLeafPath(Noderoot){// Base case: if the tree is emptyif(root==null)return0;// Initializing the variables to store the// maximum length and sumintmaxSum=int.MinValue;intmaxLen=0;// Calling the utility functionsumOfRootToLeaf(root,0,0,refmaxLen,refmaxSum);// Returning the maximum sumreturnmaxSum;}staticvoidMain(string[]args){// binary tree formation// 4// / \ // 2 5// / \ // 1 3Noderoot=newNode(4);root.left=newNode(2);root.right=newNode(5);root.left.left=newNode(1);root.left.right=newNode(3);Console.WriteLine(sumOfLongRootToLeafPath(root));}}
JavaScript
// JavaScript implementation to find the sum of nodes// on the longest path from root to leaf nodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionsumOfRootToLeaf(root,sum,length,maxLen,maxSum){// Base case: if the current node is nullif(!root){// Checking if the current path has a longer length // and update maxLen and maxSum accordinglyif(length>maxLen[0]){maxLen[0]=length;maxSum[0]=sum;}// If the lengths are equal, check if the current sum is // greater and update maxSum if necessaryelseif(length===maxLen[0]&&sum>maxSum[0]){maxSum[0]=sum;}return;}// Recursively calculating the sum of // the left and right subtreessumOfRootToLeaf(root.left,sum+root.data,length+1,maxLen,maxSum);sumOfRootToLeaf(root.right,sum+root.data,length+1,maxLen,maxSum);}// Function to calculate the sum of the longest// root to leaf pathfunctionsumOfLongRootToLeafPath(root){// Base case: if the tree is emptyif(!root)return0;// Initializing the variables to store the// maximum length and sumletmaxSum=[-Infinity];letmaxLen=[0];// Calling the utility functionsumOfRootToLeaf(root,0,0,maxLen,maxSum);// Returning the maximum sumreturnmaxSum[0];}// binary tree formation// 4// / \ // 2 5// / \ // 1 3 constroot=newNode(4);root.left=newNode(2);root.right=newNode(5);root.left.left=newNode(1);root.left.right=newNode(3);console.log(sumOfLongRootToLeafPath(root));