Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Sum of nodes on the longest path from root to leaf node

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a binary tree containing n nodes. The problem 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 maximum sum of nodes is being considered.
Examples: 
 

Input : Binary tree:
        4        
       / \       
      2   5      
     / \ / \     
    7  1 2  3    
      /
     6
Output : 13

        4        
       / \       
      2   5      
     / \ / \     
    7  1 2  3 
      /
     6

The highlighted nodes (4, 2, 1, 6) above are 
part of the longest root to leaf path having
sum = (4 + 2 + 1 + 6) = 13

 

Approach: Recursively find the length and sum of nodes of each root to leaf path and accordingly update the maximum sum.
Algorithm: 
 

sumOfLongRootToLeafPath(root, sum, len, maxLen, maxSum)
    if root == NULL
        if maxLen < len
        maxLen = len
        maxSum = sum
    else if maxLen == len && maxSum is less than sum
        maxSum = sum
        return

    sumOfLongRootToLeafPath(root-left, sum + root-data,
                           len + 1, maxLen, maxSum)
    sumOfLongRootToLeafPath(root-right, sum + root-data,
                           len + 1, maxLen, maxSum)

sumOfLongRootToLeafPathUtil(root)
    if (root == NULL)
        return 0
    
    Declare maxSum = Minimum Integer
    Declare maxLen = 0
    sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum)
    return maxSum

 

C++




// C++ implementation to find the sum of nodes
// on the longest path from root to leaf node
#include <bits/stdc++.h>
 
using namespace std;
 
// Node of a binary tree
struct Node {
    int data;
    Node* left, *right;
};
 
// function to get a new node
Node* getNode(int data)
{
    // allocate memory for the node
    Node* newNode = (Node*)malloc(sizeof(Node));
 
    // put in the data
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
 
// function to find the sum of nodes on the
// longest path from root to leaf node
void sumOfLongRootToLeafPath(Node* root, int sum,
                      int len, int& maxLen, int& maxSum)
{
    // if true, then we have traversed a
    // root to leaf path
    if (!root) {
        // update maximum length and maximum sum
        // according to the given conditions
        if (maxLen < len) {
            maxLen = len;
            maxSum = sum;
        } else if (maxLen == len && maxSum < sum)
            maxSum = sum;
        return;
    }
 
    // recur for left subtree
    sumOfLongRootToLeafPath(root->left, sum + root->data,
                            len + 1, maxLen, maxSum);
 
    // recur for right subtree
    sumOfLongRootToLeafPath(root->right, sum + root->data,
                            len + 1, maxLen, maxSum);
}
 
// utility function to find the sum of nodes on
// the longest path from root to leaf node
int sumOfLongRootToLeafPathUtil(Node* root)
{
    // if tree is NULL, then sum is 0
    if (!root)
        return 0;
 
    int maxSum = INT_MIN, maxLen = 0;
 
    // finding the maximum sum 'maxSum' for the
    // maximum length root to leaf path
    sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum);
 
    // required maximum sum
    return maxSum;
}
 
// Driver program to test above
int main()
{
    // binary tree formation
    Node* root = getNode(4);         /*        4        */
    root->left = getNode(2);         /*       / \       */
    root->right = getNode(5);        /*      2   5      */
    root->left->left = getNode(7);   /*     / \ / \     */
    root->left->right = getNode(1);  /*    7  1 2  3    */
    root->right->left = getNode(2);  /*      /          */
    root->right->right = getNode(3); /*     6           */
    root->left->right->left = getNode(6);
 
    cout << "Sum = "
         << sumOfLongRootToLeafPathUtil(root);
 
    return 0;
}


Java




// Java implementation to find the sum of nodes
// on the longest path from root to leaf node
public class GFG
{                       
    // Node of a binary tree
    static class Node {
        int data;
        Node left, right;
         
        Node(int data){
            this.data = data;
            left = null;
            right = null;
        }
    }
    static int maxLen;
    static int maxSum;
     
    // function to find the sum of nodes on the
    // longest path from root to leaf node
    static void sumOfLongRootToLeafPath(Node root, int sum,
                                         int len)
    {
        // if true, then we have traversed a
        // root to leaf path
        if (root == null) {
            // update maximum length and maximum sum
            // according to the given conditions
            if (maxLen < len) {
                maxLen = len;
                maxSum = sum;
            } else if (maxLen == len && maxSum < sum)
                maxSum = sum;
            return;
        }
         
         
        // recur for left subtree
        sumOfLongRootToLeafPath(root.left, sum + root.data,
                                len + 1);
         
        sumOfLongRootToLeafPath(root.right, sum + root.data,
                                len + 1);
         
    }
      
    // utility function to find the sum of nodes on
    // the longest path from root to leaf node
    static int sumOfLongRootToLeafPathUtil(Node root)
    {
        // if tree is NULL, then sum is 0
        if (root == null)
            return 0;
      
        maxSum = Integer.MIN_VALUE;
        maxLen = 0;
      
        // finding the maximum sum 'maxSum' for the
        // maximum length root to leaf path
        sumOfLongRootToLeafPath(root, 0, 0);
      
        // required maximum sum
        return maxSum;
    }
      
    // Driver program to test above
    public static void main(String args[])
    {
        // binary tree formation
        Node root = new Node(4);         /*        4        */
        root.left = new Node(2);         /*       / \       */
        root.right = new Node(5);        /*      2   5      */
        root.left.left = new Node(7);    /*     / \ / \     */
        root.left.right = new Node(1);   /*    7  1 2  3    */
        root.right.left = new Node(2);   /*      /          */
        root.right.right = new Node(3);  /*     6           */
        root.left.right.left = new Node(6);
      
        System.out.println( "Sum = "
             + sumOfLongRootToLeafPathUtil(root));
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 implementation to find the 
# Sum of nodes on the longest path
# from root to leaf nodes
 
# function to get a new node
class getNode:
    def __init__(self, data):
 
        # put in the data
        self.data = data
        self.left = self.right = None
 
# function to find the Sum of nodes on the
# longest path from root to leaf node
def SumOfLongRootToLeafPath(root, Sum, Len,
                            maxLen, maxSum):
                                 
    # if true, then we have traversed a
    # root to leaf path
    if (not root):
         
        # update maximum Length and maximum Sum
        # according to the given conditions
        if (maxLen[0] < Len):
            maxLen[0] = Len
            maxSum[0] = Sum
        else if (maxLen[0]== Len and
              maxSum[0] < Sum):
            maxSum[0] = Sum
        return
 
    # recur for left subtree
    SumOfLongRootToLeafPath(root.left, Sum + root.data,
                            Len + 1, maxLen, maxSum)
 
    # recur for right subtree
    SumOfLongRootToLeafPath(root.right, Sum + root.data,
                            Len + 1, maxLen, maxSum)
 
# utility function to find the Sum of nodes on
# the longest path from root to leaf node
def SumOfLongRootToLeafPathUtil(root):
     
    # if tree is NULL, then Sum is 0
    if (not root):
        return 0
 
    maxSum = [-999999999999]
    maxLen = [0]
 
    # finding the maximum Sum 'maxSum' for
    # the maximum Length root to leaf path
    SumOfLongRootToLeafPath(root, 0, 0,
                            maxLen, maxSum)
 
    # required maximum Sum
    return maxSum[0]
 
# Driver Code
if __name__ == '__main__':
     
    # binary tree formation
    root = getNode(4)         #     4    
    root.left = getNode(2)         #     / \    
    root.right = getNode(5)     #     2 5    
    root.left.left = getNode(7) #     / \ / \    
    root.left.right = getNode(1) # 7 1 2 3
    root.right.left = getNode(2) #     /        
    root.right.right = getNode(3) #     6        
    root.left.right.left = getNode(6)
 
    print("Sum = ", SumOfLongRootToLeafPathUtil(root))
     
# This code is contributed by PranchalK


C#




using System;
 
// c# implementation to find the sum of nodes
// on the longest path from root to leaf node
public class GFG
{
    // Node of a binary tree
    public class Node
    {
        public int data;
        public Node left, right;
 
        public Node(int data)
        {
            this.data = data;
            left = null;
            right = null;
        }
    }
    public static int maxLen;
    public static int maxSum;
 
    // function to find the sum of nodes on the
    // longest path from root to leaf node
    public static void sumOfLongRootToLeafPath(Node root, int sum, int len)
    {
        // if true, then we have traversed a
        // root to leaf path
        if (root == null)
        {
            // update maximum length and maximum sum
            // according to the given conditions
            if (maxLen < len)
            {
                maxLen = len;
                maxSum = sum;
            }
            else if (maxLen == len && maxSum < sum)
            {
                maxSum = sum;
            }
            return;
        }
 
 
        // recur for left subtree
        sumOfLongRootToLeafPath(root.left, sum + root.data, len + 1);
 
        sumOfLongRootToLeafPath(root.right, sum + root.data, len + 1);
 
    }
 
    // utility function to find the sum of nodes on
    // the longest path from root to leaf node
    public static int sumOfLongRootToLeafPathUtil(Node root)
    {
        // if tree is NULL, then sum is 0
        if (root == null)
        {
            return 0;
        }
 
        maxSum = int.MinValue;
        maxLen = 0;
 
        // finding the maximum sum 'maxSum' for the
        // maximum length root to leaf path
        sumOfLongRootToLeafPath(root, 0, 0);
 
        // required maximum sum
        return maxSum;
    }
 
    // Driver program to test above
    public static void Main(string[] args)
    {
        // binary tree formation
        Node root = new Node(4); //        4
        root.left = new Node(2); //       / \
        root.right = new Node(5); //      2   5
        root.left.left = new Node(7); //     / \ / \
        root.left.right = new Node(1); //    7  1 2  3
        root.right.left = new Node(2); //      /
        root.right.right = new Node(3); //     6
        root.left.right.left = new Node(6);
 
        Console.WriteLine("Sum = " + sumOfLongRootToLeafPathUtil(root));
    }
}
 
  // This code is contributed by Shrikant13


Javascript




<script>
// javascript implementation to find the sum of nodes
// on the longest path from root to leaf node
          
    // Node of a binary tree
     class Node {
            constructor(val) {
                this.data = val;
                this.left = null;
                this.right = null;
            }
        }
    var maxLen;
    var maxSum;
     
    // function to find the sum of nodes on the
    // longest path from root to leaf node
    function sumOfLongRootToLeafPath(root , sum,
                                          len)
    {
        // if true, then we have traversed a
        // root to leaf path
        if (root == null)
        {
         
            // update maximum length and maximum sum
            // according to the given conditions
            if (maxLen < len) {
                maxLen = len;
                maxSum = sum;
            } else if (maxLen == len && maxSum < sum)
                maxSum = sum;
            return;
        }
         
         
        // recur for left subtree
        sumOfLongRootToLeafPath(root.left, sum + root.data,
                                len + 1);
         
        sumOfLongRootToLeafPath(root.right, sum + root.data,
                                len + 1);
         
    }
      
    // utility function to find the sum of nodes on
    // the longest path from root to leaf node
    function sumOfLongRootToLeafPathUtil(root)
    {
     
        // if tree is NULL, then sum is 0
        if (root == null)
            return 0;
      
        maxSum = Number.MIN_VALUE;
        maxLen = 0;
      
        // finding the maximum sum 'maxSum' for the
        // maximum length root to leaf path
        sumOfLongRootToLeafPath(root, 0, 0);
      
        // required maximum sum
        return maxSum;
    }
      
    // Driver program to test above
     
        // binary tree formation
        var root = new Node(4);         /*        4        */
        root.left = new Node(2);         /*       / \       */
        root.right = new Node(5);        /*      2   5      */
        root.left.left = new Node(7);    /*     / \ / \     */
        root.left.right = new Node(1);   /*    7  1 2  3    */
        root.right.left = new Node(2);   /*      /          */
        root.right.right = new Node(3);  /*     6           */
        root.left.right.left = new Node(6);
      
        document.write( "Sum = "
             + sumOfLongRootToLeafPathUtil(root));
 
// This code is contributed by gauravrajput1
</script>


Output

Sum = 13

Time Complexity: O(n) 

Auxiliary Space: O(h) where h is the height of the binary tree.

Another Approach: Using level order traversal

  1. Create a structure containing the current Node, level and sum in the path.
  2. Push the root element with level 0 and sum as the root’s data.
  3. Pop the front element and update the maximum level sum and maximum level if needed.
  4. Push the left and right nodes if exists.
  5. Do the same for all the nodes in tree.

C++




#include <bits/stdc++.h>
using namespace std;
 
//Building a tree node having left and right pointers set to null initially
struct Node
{
  Node* left;
  Node* right;
  int data;
  //constructor to set the data of the newly created tree node
  Node(int element){
     data = element;
     this->left = nullptr;
     this->right = nullptr;
  }
};
 
int longestPathLeaf(Node* root){
   
  /* structure to store current Node,it's level and sum in the path*/
  struct Element{
    Node* data;
    int level;
    int sum;
  };
   
  /*
    maxSumLevel stores maximum sum so far in the path
    maxLevel stores maximum level so far
  */
  int maxSumLevel = root->data,maxLevel = 0;
 
  /* queue to implement level order traversal */
   
  list<Element> que;
  Element e;
   
  /* Each element variable stores the current Node, it's level, sum in the path */
 
  e.data = root;
  e.level = 0;
  e.sum = root->data;
   
  /* push the root element*/
  que.push_back(e);
   
  /* do level order traversal on the tree*/
  while(!que.empty()){
 
     Element front = que.front();
     Node* curr = front.data;
     que.pop_front();
      
     /* if the level of current front element is greater than the maxLevel so far then update maxSum*/
     if(front.level > maxLevel){
        maxSumLevel = front.sum;
        maxLevel = front.level;
     }
     /* if another path competes then update if the sum is greater than the previous path of same height*/
     else if(front.level == maxLevel && front.sum > maxSumLevel)
        maxSumLevel = front.sum;
 
     /* push the left element if exists*/ 
     if(curr->left){
        e.data = curr->left;
        e.sum = e.data->data;
        e.sum +=  front.sum;
        e.level = front.level+1;
        que.push_back(e);
     }
     /*push the right element if exists*/
     if(curr->right){
        e.data = curr->right;
        e.sum = e.data->data;
        e.sum +=  front.sum;
        e.level = front.level+1;
        que.push_back(e);
     }
  }
 
  /*return the answer*/
  return maxSumLevel;
}
//Helper function
int main() {
   
  Node* root = new Node(4);        
  root->left = new Node(2);        
  root->right = new Node(5);       
  root->left->left = new Node(7);  
  root->left->right = new Node(1); 
  root->right->left = new Node(2);
  root->right->right = new Node(3);
  root->left->right->left = new Node(6);
   
  cout << longestPathLeaf(root) << "\n";
     
  return 0;
}


Java




// Java Code to find sum of nodes on the longest path from
// root to leaf node using level order traversal
import java.util.*;
 
// Building a tree node having left and right pointers set
// to null initially
class Main {
 
    static class Node {
        Node left;
        Node right;
        int data;
        // constructor to set the data of the newly created
        // tree node
        Node(int element)
        {
            data = element;
            this.left = null;
            this.right = null;
        }
    }
 
    /* structure to store current Node,it's level and sum in
     * the path*/
    static class Element {
        Node data;
        int level;
        int sum;
    }
 
    public static int longestPathLeaf(Node root)
    {
        /*
          maxSumLevel stores maximum sum so far in the path
          maxLevel stores maximum level so far
        */
        int maxSumLevel = root.data;
        int maxLevel = 0;
 
        /* queue to implement level order traversal */
        Queue<Element> que = new LinkedList<>();
        Element e = new Element();
 
        /* Each element variable stores the current Node,
         * it's level, sum in the path */
 
        e.data = root;
        e.level = 0;
        e.sum = root.data;
 
        /* push the root element*/
        que.add(e);
 
        /* do level order traversal on the tree*/
        while (!que.isEmpty()) {
            Element front = que.poll();
            Node curr = front.data;
 
            /* if the level of current front element is
             * greater than the maxLevel so far then update
             * maxSum*/
            if (front.level > maxLevel) {
                maxSumLevel = front.sum;
                maxLevel = front.level;
            }
 
            /* if another path competes then update if the
             * sum is greater than the previous path of same
             * height*/
            else if (front.level == maxLevel
                     && front.sum > maxSumLevel) {
                maxSumLevel = front.sum;
            }
 
            /* push the left element if exists*/
            if (curr.left != null) {
                e = new Element();
                e.data = curr.left;
                e.sum = e.data.data;
                e.sum += front.sum;
                e.level = front.level + 1;
                que.add(e);
            }
 
            /*push the right element if exists*/
            if (curr.right != null) {
                e = new Element();
                e.data = curr.right;
                e.sum = e.data.data;
                e.sum += front.sum;
                e.level = front.level + 1;
                que.add(e);
            }
        }
        /*return the answer*/
        return maxSumLevel;
    }
    // Helper function
    public static void main(String[] args)
    {
 
        Node root = new Node(4);
        root.left = new Node(2);
        root.right = new Node(5);
        root.left.left = new Node(7);
        root.left.right = new Node(1);
        root.right.left = new Node(2);
        root.right.right = new Node(3);
        root.left.right.left = new Node(6);
 
        System.out.println(longestPathLeaf(root));
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Python3




# Python Code to find sum of nodes on the longest path from root to leaf node
# using level order traversal
 
# Building a tree node having left and right pointers set to null initially
class Node:
    def __init__(self, element):
        self.data = element
        self.left = None
        self.right = None
 
# To store current Node,it's level and sum in the path
class Element:
    def __init__(self, data, level, sum):
        self.data = data
        self.level = level
        self.sum = sum
 
 
class Solution:
    def longestPathLeaf(self, root):
 
        # maxSumLevel stores maximum sum so far in the path
        # maxLevel stores maximum level so far
 
        maxSumLevel = root.data
        maxLevel = 0
 
        # queue to implement level order traversal
        que = []
 
        # Each element variable stores the current Node, it's level, sum in the path
        e = Element(root, 0, root.data)
 
        # push the root element
        que.append(e)
 
        # do level order traversal on the tree
        while len(que) != 0:
 
            front = que[0]
            curr = front.data
            del que[0]
 
           # if the level of current front element is greater than the maxLevel so far then update maxSum
            if front.level > maxLevel:
                maxSumLevel = front.sum
                maxLevel = front.level
 
                # if another path competes then update if the sum is greater than the previous path of same height
            elif front.level == maxLevel and front.sum > maxSumLevel:
                maxSumLevel = front.sum
 
                # push the left element if exists
            if curr.left != None:
                e = Element(curr.left, front.level+1, curr.left.data+front.sum)
                que.append(e)
 
                # push the right element if exists
            if curr.right != None:
                e = Element(curr.right, front.level+1,
                            curr.right.data+front.sum)
                que.append(e)
 
        # return the answer
        return maxSumLevel
 
 
# Helper function
if __name__ == '__main__':
    s = Solution()
    root = Node(4)
    root.left = Node(2)
    root.right = Node(5)
    root.left.left = Node(7)
    root.left.right = Node(1)
    root.right.left = Node(2)
    root.right.right = Node(3)
    root.left.right.left = Node(6)
 
    print(s.longestPathLeaf(root))
 
# This code is contributed by Tapesh(tapeshdua420)


C#




// C# program to find sum of nodes on the longest path from
// root to leaf node using level order traversal
using System;
using System.Collections;
 
// Building a tree node having left and right pointers set
// to null initially
class Node {
 
  public Node left;
  public Node right;
  public int data;
 
  // constructor to set the data of the newly created
  // tree node
  public Node(int element)
  {
 
    data = element;
    this.left = null;
    this.right = null;
  }
}
/* structure to store current Node,it's level and sum in
 * the path*/
class Element {
 
  public Node data;
  public int level;
  public int sum;
}
 
class GFG {
  public static int longestPathLeaf(Node root)
  {
    /*
          maxSumLevel stores maximum sum so far in the path
          maxLevel stores maximum level so far
        */
    int maxSumLevel = root.data;
    int maxLevel = 0;
 
    /* queue to implement level order traversal */
    Queue que = new Queue();
    Element e = new Element();
 
    /* Each element variable stores the current Node,
         * it's level, sum in the path */
 
    e.data = root;
    e.level = 0;
    e.sum = root.data;
 
    /* push the root element*/
    que.Enqueue(e);
 
    /* do level order traversal on the tree*/
    while (que.Count != 0) {
      dynamic front = que.Dequeue();
      Node curr = front.data;
 
      /* if the level of current front element is
             * greater than the maxLevel so far then update
             * maxSum*/
      if (front.level > maxLevel) {
        maxSumLevel = front.sum;
        maxLevel = front.level;
      }
 
      /* if another path competes then update if the
             * sum is greater than the previous path of same
             * height*/
      else if (front.level == maxLevel
               && front.sum > maxSumLevel) {
        maxSumLevel = front.sum;
      }
 
      /* push the left element if exists*/
      if (curr.left != null) {
        e = new Element();
        e.data = curr.left;
        e.sum = e.data.data;
        e.sum += front.sum;
        e.level = front.level + 1;
        que.Enqueue(e);
      }
 
      /*push the right element if exists*/
      if (curr.right != null) {
        e = new Element();
        e.data = curr.right;
        e.sum = e.data.data;
        e.sum += front.sum;
        e.level = front.level + 1;
        que.Enqueue(e);
      }
    }
    /*return the answer*/
    return maxSumLevel;
  }
  // Helper function
  public static void Main(string[] args)
  {
 
    Node root = new Node(4);
    root.left = new Node(2);
    root.right = new Node(5);
    root.left.left = new Node(7);
    root.left.right = new Node(1);
    root.right.left = new Node(2);
    root.right.right = new Node(3);
    root.left.right.left = new Node(6);
 
    Console.WriteLine(longestPathLeaf(root));
  }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Javascript




// Javascript code to find sum of nodes on the longest path from root to leaf node
// using level order traversal
 
class Node {
    constructor(element) {
        this.data = element;
        this.left = null;
        this.right = null;
    }
}
 
class Element {
    constructor(data, level, sum) {
        this.data = data;
        this.level = level;
        this.sum = sum;
    }
}
 
class Solution {
    longestPathLeaf(root) {
 
        // maxSumLevel stores maximum sum so far in the path
        // maxLevel stores maximum level so far
 
        let maxSumLevel = root.data;
        let maxLevel = 0;
 
        // queue to implement level order traversal
        let que = [];
 
        // Each element variable stores the current Node, it's level, sum in the path
        let e = new Element(root, 0, root.data);
 
        // push the root element
        que.push(e);
 
        // do level order traversal on the tree
        while (que.length !== 0) {
 
            let front = que[0];
            let curr = front.data;
            que.shift();
 
            // if the level of current front element is greater than the maxLevel so far then update maxSum
            if (front.level > maxLevel) {
                maxSumLevel = front.sum;
                maxLevel = front.level;
            }
            // if another path competes then update if the sum is greater than the previous path of same height
            else if (front.level === maxLevel && front.sum > maxSumLevel) {
                maxSumLevel = front.sum;
            }
 
            // push the left element if exists
            if (curr.left !== null) {
                e = new Element(curr.left, front.level + 1, curr.left.data + front.sum);
                que.push(e);
            }
 
            // push the right element if exists
            if (curr.right !== null) {
                e = new Element(curr.right, front.level + 1, curr.right.data + front.sum);
                que.push(e);
            }
        }
 
        // return the answer
        return maxSumLevel;
    }
}
 
// Helper function
const s = new Solution();
const root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(7);
root.left.right = new Node(1);
root.right.left = new Node(2);
root.right.right = new Node(3);
root.left.right.left = new Node(6);
 
console.log(s.longestPathLeaf(root));


Output

13

Time Complexity: O(N)
Auxiliary Space: O(N)

Contributed by Manjukrishna

Using Breadth-First Search (BFS):

In this approach, we perform a BFS on the tree and keep track of the maximum depth and the sum of nodes at that depth. We can calculate the sum of longest bloodline by adding the maximum depth to the sum of nodes at that depth.

Follow the steps below to implement the above approach:

  1. Initialize a variable max_sum to the minimum integer value.
  2. Create an empty queue for BFS traversal.
  3. Enqueue the root node to the queue.
  4. While the queue is not empty, do the following:
    a. Initialize a variable level_sum to 0.
    b. Get the number of nodes in the current level.
    c. For each node in the current level, do the following:
    i. Dequeue a node from the queue.
    ii. Add the node’s data to the level_sum.
    iii. Enqueue the left child of the node to the queue if it exists.
    iv. Enqueue the right child of the node to the queue if it exists.
    d. Update the max_sum with the level_sum if it’s greater.
  5. Return the max_sum

Below is the implementation of the above approach:

C++




// C++ code to implement BFS approach
#include <bits/stdc++.h>
using namespace std;
 
// Define a struct to represent a node of the tree
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Function to create a new node with the given data
Node* newNode(int data) {
    Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}
 
// Function to perform BFS on the tree and calculate the sum of longest bloodline
int bfs(Node* root) {
    int max_sum = INT_MIN;  // Initialize max_sum to the minimum integer value
    queue<Node*> q;  // Create an empty queue for BFS traversal
    q.push(root);  // Enqueue the root node
    while (!q.empty()) {
        int level_sum = 0;  // Initialize the level_sum to 0
        int n = q.size();  // Get the number of nodes in the current level
        for (int i = 0; i < n; i++) {
            Node* node = q.front();  // Dequeue a node from the queue
            q.pop();
            level_sum += node->data;  // Add the node's data to the level_sum
            if (node->left) q.push(node->left);  // Enqueue the left child of the node if it exists
            if (node->right) q.push(node->right);  // Enqueue the right child of the node if it exists
        }
        max_sum = max(max_sum, level_sum);  // Update the max_sum with the level_sum if it's greater
    }
    return max_sum;  // Return the max_sum
}
 
// Driver code
int main() {
    // Create the tree
    Node* root = newNode(4);
    root->left = newNode(2);
    root->right = newNode(5);
    root->left->left = newNode(7);
    root->left->right = newNode(1);
    root->right->left = newNode(2);
    root->right->right = newNode(3);
    root->left->right->left = newNode(6);
 
    // Calculate the sum of longest bloodline using BFS
    int sum = bfs(root);
 
    // Print the result
    cout << sum << endl;
 
    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot


Python3




from collections import deque
 
# Define a class to represent a node of the tree
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to perform BFS on the tree and calculate the sum of longest bloodline
def bfs(root):
    max_sum = float('-inf'# Initialize max_sum to negative infinity
    q = deque()  # Create an empty queue for BFS traversal
    q.append(root)  # Enqueue the root node
    while q:
        level_sum = 0  # Initialize the level_sum to 0
        n = len(q)  # Get the number of nodes in the current level
        for i in range(n):
            node = q.popleft()  # Dequeue a node from the queue
            level_sum += node.data  # Add the node's data to the level_sum
            if node.left: q.append(node.left)  # Enqueue the left child of the node if it exists
            if node.right: q.append(node.right)  # Enqueue the right child of the node if it exists
        max_sum = max(max_sum, level_sum)  # Update the max_sum with the level_sum if it's greater
    return max_sum  # Return the max_sum
 
# Driver code
if __name__ == '__main__':
    # Create the tree
    root = Node(4)
    root.left = Node(2)
    root.right = Node(5)
    root.left.left = Node(7)
    root.left.right = Node(1)
    root.right.left = Node(2)
    root.right.right = Node(3)
    root.left.right.left = Node(6)
 
    # Calculate the sum of longest bloodline using BFS
    sum = bfs(root)
 
    # Print the result
    print(sum)


Javascript




// Define a class to represent a node of the tree
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// Function to perform BFS on the tree and calculate the sum of longest bloodline
function bfs(root) {
    let max_sum = Number.MIN_SAFE_INTEGER;  // Initialize max_sum to the minimum safe integer value
    let q = [];  // Create an empty queue for BFS traversal
    q.push(root);  // Enqueue the root node
    while (q.length > 0) {
        let level_sum = 0;  // Initialize the level_sum to 0
        let n = q.length;  // Get the number of nodes in the current level
        for (let i = 0; i < n; i++) {
            let node = q.shift();  // Dequeue a node from the queue
            level_sum += node.data;  // Add the node's data to the level_sum
            if (node.left) q.push(node.left);  // Enqueue the left child of the node if it exists
            if (node.right) q.push(node.right);  // Enqueue the right child of the node if it exists
        }
        max_sum = Math.max(max_sum, level_sum);  // Update the max_sum with the level_sum if it's greater
    }
    return max_sum;  // Return the max_sum
}
 
// Create the tree
let root = new Node(4);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(7);
root.left.right = new Node(1);
root.right.left = new Node(2);
root.right.right = new Node(3);
root.left.right.left = new Node(6);
 
// Calculate the sum of longest bloodline using BFS
let sum = bfs(root);
 
// Print the result
console.log(sum);


Output

13

Time Complexity: O(N), where N is the number of nodes in the tree.
Space Complexity: O(W), where W is the maximum width of the tree (queue size).

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Last Updated : 17 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials