Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it.
Examples:
Input : 4
/ \
2 -5
/ \ /\
-1 3 -2 6
Output: 6
Explanation :
Sum of all nodes of 0'th level is 4
Sum of all nodes of 1'th level is -3
Sum of all nodes of 0'th level is 6
Hence maximum sum is 6
Input : 1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output : 17
This problem is a variation of the maximum width problem. The idea is to do a level order traversal of the tree. While doing traversal, process nodes of different levels separately. For every level being processed, compute the sum of nodes in the level and keep track of the maximum sum.
Below is the implementation of the above idea:
// A queue based C++ program to find maximum sum // of a level in Binary Tree #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 find the maximum sum of a level in tree // using level order traversal int maxLevelSum( struct Node* root)
{ // Base case
if (root == NULL)
return 0;
// Initialize result
int result = root->data;
// Do Level order traversal keeping track of 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 an node from queue
Node* temp = q.front();
q.pop();
// Add this node's value to current sum.
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 node count 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);
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
cout << "Maximum level sum is " << maxLevelSum(root)
<< endl;
return 0;
} |
// A queue based Java program to find maximum // sum of a level in Binary Tree 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 find the maximum // sum of a level in tree // using level order traversal static int maxLevelSum(Node root)
{ // Base case
if (root == null )
return 0 ;
// Initialize result
int result = root.data;
// Do Level order traversal keeping
// track of 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 an node from queue
Node temp = q.poll();
// Add this node's value
// to current sum.
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 node
// count value
result = Math.max(sum, result);
}
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 );
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
System.out.println( "Maximum level sum is " +
maxLevelSum(root));
} } // This code is contributed by sanjeev2552 |
# A queue based Python3 program to find # maximum sum of a level in Binary Tree from collections import deque
# A binary tree node has data, pointer # to left child and a pointer to right # child class Node:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
# Function to find the maximum sum # of a level in tree # using level order traversal def maxLevelSum(root):
# Base case
if (root = = None ):
return 0
# Initialize result
result = root.data
# Do Level order traversal keeping
# track of number
# of nodes at every level.
q = deque()
q.append(root)
while ( len (q) > 0 ):
# Get the size of queue when the
# level order traversal for one
# level finishes
count = len (q)
# Iterate for all the nodes in
# the queue currently
sum = 0
while (count > 0 ):
# Dequeue an node from queue
temp = q.popleft()
# Add this node's value to current sum.
sum = sum + temp.data
# Enqueue left and right children of
# dequeued node
if (temp.left ! = None ):
q.append(temp.left)
if (temp.right ! = None ):
q.append(temp.right)
count - = 1 # Update the maximum node count 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 )
# Constructed Binary tree is:
# 1
# / \
# 2 3
# / \ \
# 4 5 8
# / \
# 6 7
print ( "Maximum level sum is" , maxLevelSum(root))
# This code is contributed by mohit kumar 29 |
// A queue based C# program to find maximum // sum of a level in Binary Tree using System;
using System.Collections.Generic;
class GFG
{ // A binary tree node has data, pointer
// to left child and a pointer to right
// child
public
class Node
{
public
int data;
public
Node left, right;
public Node( int data)
{
this .data = data;
this .left = this .right = null ;
}
};
// Function to find the maximum
// sum of a level in tree
// using level order traversal
static int maxLevelSum(Node root)
{
// Base case
if (root == null )
return 0;
// Initialize result
int result = root.data;
// Do Level order traversal keeping
// track of number of nodes at every
// level.
Queue<Node> q = new Queue<Node>();
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 an node from queue
Node temp = q.Dequeue();
// Add this node's value
// to current sum.
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 node
// count value
result = Math.Max(sum, result);
}
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);
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
Console.WriteLine( "Maximum level sum is " +
maxLevelSum(root));
}
} // This code is contributed by gauravrajput1 |
<script> // A queue based Javascript program to find maximum // sum of a level in Binary Tree // A binary tree node has data, pointer
// to left child and a pointer to right // child class Node
{
constructor(data)
{
this .data = data;
this .left = this .right = null ;
}
}
// Function to find the maximum // sum of a level in tree // using level order traversal function maxLevelSum(root)
{ // Base case
if (root == null )
return 0;
// Initialize result
let result = root.data;
// Do Level order traversal keeping
// track of 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 an node from queue
let temp = q.shift();
// Add this node's value
// to current sum.
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 node
// count value
result = Math.max(sum, result);
}
return result;
} // Driver code 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);
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
document.write( "Maximum level sum is " +
maxLevelSum(root));
// This code is contributed by unknown2108
</script> |
Maximum level sum is 17
Complexity Analysis:
Time Complexity: O(N) where N is the total number of nodes in the tree.
In level order traversal, every node of the tree is processed once, and hence the complexity due to the level order traversal is O(N) if there are total N nodes in the tree. Also, while processing every node, we are maintaining the sum at each level, however, this does not affect the overall time complexity. Therefore, the time complexity is O(N).
Auxiliary Space: O(w) where w is the maximum width of the tree.
In level order traversal, a queue is maintained whose maximum size at any moment can go up to the maximum width of the binary tree.
Using Recursion Without Queue:-
- We will use recursion and do any dfs of the tree.
- As in dfs we will move downwards of the tree so while moving we will take care of the level of the tree
- We will add the node value to the current level of the tree
- In the end we will return the maximum sum from all level
Implementation:-
- We will start traversal by level 0 that is from root
- From root we will move downwards using recursion and while moving we will increase the level of the tree by +1.
- We will take a unordered_map to store the sum of the current level
- In the end we will return the maximum value from the map.
// A queue based C++ program to find maximum sum // of a level in Binary Tree #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 get sum or each level void dfs(Node* root, int level,unordered_map< int , int > &mm)
{ //base condition
if (!root) return ;
//adding root value to its level sum
mm[level]+=root->data;
//increasing level
level++;
//moving left
dfs(root->left,level,mm);
//moving right
dfs(root->right,level,mm);
} // Function to find the maximum sum of a level in tree // using level order traversal int maxLevelSum( struct Node* root)
{ // Base case
if (root == NULL)
return 0;
//map to store sum of each level
unordered_map< int , int > mm;
//calling function
dfs(root,0,mm);
//variable to store answer
int result = INT_MIN;
//iterating over map
for ( auto x:mm)result = max(x.second,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);
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
cout << "Maximum level sum is " << maxLevelSum(root)
<< endl;
return 0;
} //code contributed by shubhamrajput6156 |
import java.util.*;
// A binary tree node has data, a pointer to the left child, // and a pointer to the right child class Node {
int data;
Node left, right;
// Constructor to create a new node
Node( int data) {
this .data = data;
left = right = null ;
}
} class GFG {
// Function to get the sum for each level
static void dfs(Node root, int level, Map<Integer, Integer> mm) {
// Base condition
if (root == null ) return ;
// Adding the root value to its level sum
mm.put(level, mm.getOrDefault(level, 0 ) + root.data);
// Increasing level
level++;
// Moving left
dfs(root.left, level, mm);
// Moving right
dfs(root.right, level, mm);
}
// Function to find the maximum sum of a level in
// the tree using level order traversal
static int maxLevelSum(Node root) {
// Base case
if (root == null ) return 0 ;
// Map to store the sum of each level
Map<Integer, Integer> mm = new HashMap<>();
// Calling the dfs function
dfs(root, 0 , mm);
// Variable to store the answer
int result = Integer.MIN_VALUE;
// Iterating over the map
for (Map.Entry<Integer, Integer> entry : mm.entrySet()) {
result = Math.max(entry.getValue(), result);
}
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 );
// Constructed binary tree is:
// 1
// / \
// 2 3
// / \ \
// 4 5 8
// / \
// 6 7
System.out.println( "Maximum level sum is " + maxLevelSum(root));
}
} |
# A binary tree node has data, left and right pointers class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
# Function to get sum of each level def dfs(root, level, mm):
# Base condition
if not root:
return
# Adding root value to its level sum
mm[level] = mm.get(level, 0 ) + root.data
# Increasing level
level + = 1
# Moving left
dfs(root.left, level, mm)
# Moving right
dfs(root.right, level, mm)
# Function to find the maximum sum of a level in the tree def maxLevelSum(root):
# Base case
if not root:
return 0
# Map to store the sum of each level
mm = {}
# Calling the function to calculate the sum of each level
dfs(root, 0 , mm)
# Variable to store the answer
result = float ( '-inf' )
# Iterating over the map to find the maximum sum
for val in mm.values():
result = max (result, val)
return result
# Helper function to allocate a new node with the given data and NULL left and right pointers def newNode(data):
node = Node(data)
return node
# Driver code if __name__ = = "__main__" :
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 )
"""
Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
"""
print ( "Maximum level sum is" , maxLevelSum(root))
|
using System;
using System.Collections.Generic;
class Node
{ public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
} public class MainClass
{ // Function to get sum of each level
static void DFS(Node root, int level, Dictionary< int , int > mm)
{
// Base condition
if (root == null )
return ;
// Adding root value to its level sum
if (mm.ContainsKey(level))
mm[level] += root.data;
else
mm[level] = root.data;
// Increasing level
level++;
// Moving left
DFS(root.left, level, mm);
// Moving right
DFS(root.right, level, mm);
}
// Function to find the maximum sum of a level in the tree
static int MaxLevelSum(Node root)
{
// Base case
if (root == null )
return 0;
// Dictionary to store the sum of each level
Dictionary< int , int > mm = new Dictionary< int , int >();
// Calling the function to calculate the sum of each level
DFS(root, 0, mm);
// Variable to store the answer
int result = int .MinValue;
// Iterating over the dictionary to find the maximum sum
foreach ( var val in mm.Values)
{
result = Math.Max(result, val);
}
return result;
}
// Helper function to allocate a new node with the given data and NULL left and right pointers
static Node NewNode( int data)
{
Node node = new Node(data);
return node;
}
// Driver code
public static void Main( string [] args)
{
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);
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
Console.WriteLine( "Maximum level sum is " + MaxLevelSum(root));
}
} |
class Node { constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
} // Function to get sum of each level function dfs(root, level, mm) {
// Base condition
if (!root) {
return ;
}
// Adding root value to its level sum
mm[level] = (mm[level] || 0) + root.data;
// Increasing level
level++;
// Moving left
dfs(root.left, level, mm);
// Moving right
dfs(root.right, level, mm);
} // Function to find the maximum sum of a level in the tree function maxLevelSum(root) {
// Base case
if (!root) {
return 0;
}
// Object to store the sum of each level
const mm = {};
// Calling the function to calculate the sum of each level
dfs(root, 0, mm);
// Variable to store the answer
let result = Number.MIN_SAFE_INTEGER;
// Iterating over the object to find the maximum sum
for (let val of Object.values(mm)) {
result = Math.max(result, val);
}
return result;
} // Helper function to allocate a new node with the given data // and NULL left and right pointers function newNode(data) {
return new Node(data);
} // Driver code const 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);
/*
Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
console.log( "Maximum level sum is" , maxLevelSum(root));
|
Output:- Maximum level sum is 17
Time Complexity:- O(N)
Space Complexity:- O(H) where H is height of tree