Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Print all Nodes of given Binary Tree at the Kth Level
Next article icon

Maximum sum of non-leaf nodes among all levels of the given binary tree

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of non-leaf nodes among all levels of the given binary tree.

Examples: 

Input:                         4                       /   \                      2    -5                     / \                      -1   3  Output: 4 Sum of all non-leaf nodes at 0th level is 4. Sum of all non-leaf nodes at 1st level is 2. Sum of all non-leaf nodes at 2nd level is 0. Hence maximum sum is 4  Input:                  1                /   \              2      3            /  \      \           4    5      8                     /   \                    6     7   Output: 8

Approach: The idea to solve the above problem is to do the level order traversal of the tree. While doing traversal, process nodes of different levels separately. For every level being processed, compute the sum of non-leaf nodes in the level and keep track of the maximum sum.

Below is the implementation of the above approach:

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // A binary tree node has data, pointer to left child // and a pointer to right child struct Node {     int data;     struct Node *left, *right; };  // Function to return the maximum sum of non-leaf nodes // at any level in tree using level order traversal int maxNonLeafNodesSum(struct Node* root) {     // Base case     if (root == NULL)         return 0;      // Initialize result     int result = 0;      // Do Level order traversal keeping track     // of the number of nodes at every level     queue<Node*> q;     q.push(root);     while (!q.empty()) {          // Get the size of queue when the level order         // traversal for one level finishes         int count = q.size();          // Iterate for all the nodes in the queue currently         int sum = 0;         while (count--) {              // Dequeue a node from queue             Node* temp = q.front();             q.pop();              // Add non-leaf node's value to current sum             if (temp->left != NULL || temp->right != NULL)                 sum = sum + temp->data;              // Enqueue left and right children of             // dequeued node             if (temp->left != NULL)                 q.push(temp->left);             if (temp->right != NULL)                 q.push(temp->right);         }          // Update the maximum sum of leaf nodes value         result = max(sum, result);     }      return result; }  // Helper function that allocates a new node with the // given data and NULL left and right pointers struct Node* newNode(int data) {     struct Node* node = new Node;     node->data = data;     node->left = node->right = NULL;     return (node); }  // Driver code int main() {     struct Node* root = newNode(1);     root->left = newNode(2);     root->right = newNode(3);     root->left->left = newNode(4);     root->left->right = newNode(5);     root->right->right = newNode(8);     root->right->right->left = newNode(6);     root->right->right->right = newNode(7);     cout << maxNonLeafNodesSum(root) << endl;      return 0; } 
Java
// Java implementation of  // the above approach import java.util.LinkedList; import java.util.Queue; class GFG{  // A binary tree node has data,  // pointer to left child // and a pointer to right child static class Node  {   int data;   Node left, right;   public Node(int data)    {     this.data = data;     this.left = this.right = null;   } };  // Function to return the maximum  // sum of non-leaf nodes  at any  // level in tree using level  // order traversal static int maxNonLeafNodesSum(Node root)  {   // Base case   if (root == null)     return 0;    // Initialize result   int result = 0;    // Do Level order traversal keeping track   // of the number of nodes at every level   Queue<Node> q = new LinkedList<>();   q.add(root);    while (!q.isEmpty())    {     // Get the size of queue      // when the level order     // traversal for one      // level finishes     int count = q.size();      // Iterate for all the nodes      // in the queue currently     int sum = 0;     while (count-- > 0)      {       // Dequeue a node        // from queue       Node temp = q.poll();        // Add non-leaf node's        // value to current sum       if (temp.left != null ||            temp.right != null)         sum = sum + temp.data;        // Enqueue left and right        // children of dequeued node       if (temp.left != null)         q.add(temp.left);       if (temp.right != null)         q.add(temp.right);     }      // Update the maximum sum      // of leaf nodes value     result = max(sum, result);   }   return result; }  static int max(int sum,                 int result)  {   if (sum > result)     return sum;   return result; }  // Driver code public static void main(String[] args)  {   Node root = new Node(1);   root.left = new Node(2);   root.right = new Node(3);   root.left.left = new Node(4);   root.left.right = new Node(5);   root.right.right = new Node(8);   root.right.right.left = new Node(6);   root.right.right.right = new Node(7);   System.out.println(maxNonLeafNodesSum(root)); }     }  // This code is contributed by sanjeev2552 
Python3
# Python3 implementation of the approach import queue  # A binary tree node has data, pointer to  # left child and a pointer to right child class Node:       def __init__(self, data):         self.data = data         self.left = None         self.right = None          # Function to return the maximum Sum of   # non-leaf nodes at any level in tree # using level order traversal  def maxNonLeafNodesSum(root):       # Base case      if root == None:         return 0      # Initialize result      result = 0      # Do Level order traversal keeping track      # of the number of nodes at every level      q = queue.Queue()     q.put(root)      while not q.empty():           # Get the size of queue when the level          # order traversal for one level finishes          count = q.qsize()           # Iterate for all the nodes          # in the queue currently          Sum = 0         while count:               # Dequeue a node from queue              temp = q.get()                           # Add non-leaf node's value to current Sum              if temp.left != None or temp.right != None:                  Sum += temp.data               # Enqueue left and right              # children of dequeued node              if temp.left != None:                  q.put(temp.left)              if temp.right != None:                  q.put(temp.right)                              count -= 1                  # Update the maximum Sum of leaf nodes value          result = max(Sum, result)           return result   # Driver code  if __name__ == "__main__":       root = Node(1)      root.left = Node(2)      root.right = Node(3)      root.left.left = Node(4)      root.left.right = Node(5)      root.right.right = Node(8)      root.right.right.left = Node(6)      root.right.right.right = Node(7)      print(maxNonLeafNodesSum(root))   # This code is contributed by Rituraj Jain 
C#
// C# implementation of  // the above approach  using System;  using System.Collections;   class GFG{   // A binary tree node has data,  // pointer to left child // and a pointer to right child class Node  {   public int data;   public Node left, right;      public Node(int data)    {     this.data = data;     this.left = this.right = null;   } };   // Function to return the maximum  // sum of non-leaf nodes  at any  // level in tree using level  // order traversal static int maxNonLeafNodesSum(Node root)  {      // Base case   if (root == null)     return 0;     // Initialize result   int result = 0;     // Do Level order traversal keeping track   // of the number of nodes at every level   Queue q = new Queue();      q.Enqueue(root);     while (q.Count != 0)    {          // Get the size of queue      // when the level order     // traversal for one      // level finishes     int count = q.Count;       // Iterate for all the nodes      // in the queue currently     int sum = 0;          while (count-- > 0)      {              // Dequeue a node        // from queue       Node temp = (Node)q.Dequeue();         // Add non-leaf node's        // value to current sum       if (temp.left != null ||            temp.right != null)         sum = sum + temp.data;         // Enqueue left and right        // children of dequeued node       if (temp.left != null)         q.Enqueue(temp.left);       if (temp.right != null)         q.Enqueue(temp.right);     }       // Update the maximum sum      // of leaf nodes value     result = max(sum, result);   }   return result; }   static int max(int sum,                 int result)  {   if (sum > result)     return sum;      return result; }   // Driver code public static void Main(string[] args)  {   Node root = new Node(1);   root.left = new Node(2);   root.right = new Node(3);   root.left.left = new Node(4);   root.left.right = new Node(5);   root.right.right = new Node(8);   root.right.right.left = new Node(6);   root.right.right.right = new Node(7);   Console.Write(maxNonLeafNodesSum(root)); }     }  // This code is contributed by rutvik_56 
JavaScript
<script>      // JavaScript implementation of the approach          // A binary tree node has data,     // pointer to left child     // and a pointer to right child     class Node     {         constructor(data) {            this.left = null;            this.right = null;            this.data = data;         }     }          // Function to return the maximum     // sum of non-leaf nodes  at any     // level in tree using level     // order traversal     function maxNonLeafNodesSum(root)     {       // Base case       if (root == null)         return 0;        // Initialize result       let result = 0;        // Do Level order traversal keeping track       // of the number of nodes at every level       let q = [];       q.push(root);        while (q.length > 0)       {         // Get the size of queue         // when the level order         // traversal for one         // level finishes         let count = q.length;          // Iterate for all the nodes         // in the queue currently         let sum = 0;         while (count-- > 0)         {           // Dequeue a node           // from queue           let temp = q[0];           q.shift();            // Add non-leaf node's           // value to current sum           if (temp.left != null ||               temp.right != null)             sum = sum + temp.data;            // Enqueue left and right           // children of dequeued node           if (temp.left != null)             q.push(temp.left);           if (temp.right != null)             q.push(temp.right);         }          // Update the maximum sum         // of leaf nodes value         result = max(sum, result);       }       return result;     }      function max(sum, result)     {       if (sum > result)         return sum;       return result;     }          let root = new Node(1);     root.left = new Node(2);     root.right = new Node(3);     root.left.left = new Node(4);     root.left.right = new Node(5);     root.right.right = new Node(8);     root.right.right.left = new Node(6);     root.right.right.right = new Node(7);     document.write(maxNonLeafNodesSum(root));  </script> 

Output: 
8

 

Time Complexity: O(N) where N is the number of nodes in the given tree.
Auxiliary Space: O(N) due to queue data structure.


Next Article
Print all Nodes of given Binary Tree at the Kth Level

S

Shivam.Pradhan
Improve
Article Tags :
  • Tree
  • DSA
  • Binary Tree
  • tree-level-order
Practice Tags :
  • Tree

Similar Reads

  • Maximum sum of leaf nodes among all levels of the given binary tree
    Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of leaf nodes among all level of the given binary tree.Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 2 Sum of all leaves at 0th level is 0. Sum of all leaves at 1st level is -5. Sum of all leaves at 2nd level
    9 min read
  • Find the maximum node at a given level in a binary tree
    Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level. The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call.
    13 min read
  • Print all Nodes of given Binary Tree at the Kth Level
    Given a binary tree and an integer K, the task is to print all the integers at the Kth level in the tree from left to right. Examples: Input: Tree in the image below, K = 3 Output: 4 5 6Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6. Input: Tree
    5 min read
  • Sum of nodes at maximum depth of a Binary Tree
    Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 While traversing the nodes compare th
    15+ min read
  • Sum of Bitwise AND of the sum of all leaf and non-leaf nodes for each level of a Binary Tree
    Given a Binary Tree consisting of N nodes, the task is to find the sum of Bitwise AND of the sum of all leaf nodes and the sum of all non-leaf nodes for each level in the given Tree. Examples: Input: Below is the given tree: 5 / \ 3 9 / \ 6 4 \ 7Output: 5Explanation: For Level 1: leaf node sum = 0,
    10 min read
  • Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
    Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from the root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7Input : root(of above tree)Output : 22Explanation:Nodes at maximum depth are 4, 5, 6, 7. So, the sum of these nodes = 22Approach: There exists a recursive
    8 min read
  • Find sum of all nodes of the given perfect binary tree
    Given a positive integer L which represents the number of levels in a perfect binary tree. Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n, where n is the number of leaf nodes. And the parent node is the sum of the two child nodes. Our task is to write a progr
    11 min read
  • Sum of all leaf nodes of binary tree
    Given a binary tree, find the sum of all the leaf nodes.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : Sum = 4 + 5 + 8 + 7 = 24 Recommended PracticeSum of Leaf NodesTry It! The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the lea
    5 min read
  • Sum of nodes in the left view of the given binary tree
    Given a binary tree, the task is to find the sum of the nodes which are visible in the left view. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left.Examples: Example 1 : The Green colored nodes represents the left view in the below Binary tree. The Left
    13 min read
  • Find the maximum element of every subtree of a Binary Tree
    Given a Binary Tree, find the maximum element of every subtree of it. Examples :Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : [4, 5, 5, 7, 6, 7, 7] Explanation: The maximum element of the subtree rooted at node 4 is 4. The maximum element of the subtree rooted at node 2 is 5. The maximum element of the
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences