Find maximum level sum in Binary Tree
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:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
};
int maxLevelSum( struct Node* root)
{
if (root == NULL)
return 0;
int result = root->data;
queue<Node*> q;
q.push(root);
while (!q.empty())
{
int count = q.size();
int sum = 0;
while (count--)
{
Node* temp = q.front();
q.pop();
sum = sum + temp->data;
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
result = max(sum, result);
}
return result;
}
struct Node* newNode( int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
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 << "Maximum level sum is " << maxLevelSum(root)
<< endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class GFG{
static class Node
{
int data;
Node left, right;
public Node( int data)
{
this .data = data;
this .left = this .right = null ;
}
};
static int maxLevelSum(Node root)
{
if (root == null )
return 0 ;
int result = root.data;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
int count = q.size();
int sum = 0 ;
while (count-- > 0 )
{
Node temp = q.poll();
sum = sum + temp.data;
if (temp.left != null )
q.add(temp.left);
if (temp.right != null )
q.add(temp.right);
}
result = Math.max(sum, result);
}
return result;
}
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( "Maximum level sum is " +
maxLevelSum(root));
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def maxLevelSum(root):
if (root = = None ):
return 0
result = root.data
q = deque()
q.append(root)
while ( len (q) > 0 ):
count = len (q)
sum = 0
while (count > 0 ):
temp = q.popleft()
sum = sum + temp.data
if (temp.left ! = None ):
q.append(temp.left)
if (temp.right ! = None ):
q.append(temp.right)
count - = 1
result = max ( sum , result)
return result
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 ( "Maximum level sum is" , maxLevelSum(root))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public
class Node
{
public
int data;
public
Node left, right;
public Node( int data)
{
this .data = data;
this .left = this .right = null ;
}
};
static int maxLevelSum(Node root)
{
if (root == null )
return 0;
int result = root.data;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count != 0)
{
int count = q.Count;
int sum = 0;
while (count --> 0)
{
Node temp = q.Dequeue();
sum = sum + temp.data;
if (temp.left != null )
q.Enqueue(temp.left);
if (temp.right != null )
q.Enqueue(temp.right);
}
result = Math.Max(sum, result);
}
return result;
}
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.WriteLine( "Maximum level sum is " +
maxLevelSum(root));
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data = data;
this .left = this .right = null ;
}
}
function maxLevelSum(root)
{
if (root == null )
return 0;
let result = root.data;
let q = [];
q.push(root);
while (q.length!=0)
{
let count = q.length;
let sum = 0;
while (count-- > 0)
{
let temp = q.shift();
sum = sum + temp.data;
if (temp.left != null )
q.push(temp.left);
if (temp.right != null )
q.push(temp.right);
}
result = Math.max(sum, result);
}
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( "Maximum level sum is " +
maxLevelSum(root));
</script>
|
Output
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.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
};
void dfs(Node* root, int level,unordered_map< int , int > &mm)
{
if (!root) return ;
mm[level]+=root->data;
level++;
dfs(root->left,level,mm);
dfs(root->right,level,mm);
}
int maxLevelSum( struct Node* root)
{
if (root == NULL)
return 0;
unordered_map< int , int > mm;
dfs(root,0,mm);
int result = INT_MIN;
for ( auto x:mm)result = max(x.second,result);
return result;
}
struct Node* newNode( int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
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 << "Maximum level sum is " << maxLevelSum(root)
<< endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
Node( int data) {
this .data = data;
left = right = null ;
}
}
class GFG {
static void dfs(Node root, int level, Map<Integer, Integer> mm) {
if (root == null ) return ;
mm.put(level, mm.getOrDefault(level, 0 ) + root.data);
level++;
dfs(root.left, level, mm);
dfs(root.right, level, mm);
}
static int maxLevelSum(Node root) {
if (root == null ) return 0 ;
Map<Integer, Integer> mm = new HashMap<>();
dfs(root, 0 , mm);
int result = Integer.MIN_VALUE;
for (Map.Entry<Integer, Integer> entry : mm.entrySet()) {
result = Math.max(entry.getValue(), result);
}
return result;
}
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( "Maximum level sum is " + maxLevelSum(root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def dfs(root, level, mm):
if not root:
return
mm[level] = mm.get(level, 0 ) + root.data
level + = 1
dfs(root.left, level, mm)
dfs(root.right, level, mm)
def maxLevelSum(root):
if not root:
return 0
mm = {}
dfs(root, 0 , mm)
result = float ( '-inf' )
for val in mm.values():
result = max (result, val)
return result
def newNode(data):
node = Node(data)
return node
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 )
print ( "Maximum level sum is" , maxLevelSum(root))
|
C#
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
{
static void DFS(Node root, int level, Dictionary< int , int > mm)
{
if (root == null )
return ;
if (mm.ContainsKey(level))
mm[level] += root.data;
else
mm[level] = root.data;
level++;
DFS(root.left, level, mm);
DFS(root.right, level, mm);
}
static int MaxLevelSum(Node root)
{
if (root == null )
return 0;
Dictionary< int , int > mm = new Dictionary< int , int >();
DFS(root, 0, mm);
int result = int .MinValue;
foreach ( var val in mm.Values)
{
result = Math.Max(result, val);
}
return result;
}
static Node NewNode( int data)
{
Node node = new Node(data);
return node;
}
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);
Console.WriteLine( "Maximum level sum is " + MaxLevelSum(root));
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function dfs(root, level, mm) {
if (!root) {
return ;
}
mm[level] = (mm[level] || 0) + root.data;
level++;
dfs(root.left, level, mm);
dfs(root.right, level, mm);
}
function maxLevelSum(root) {
if (!root) {
return 0;
}
const mm = {};
dfs(root, 0, mm);
let result = Number.MIN_SAFE_INTEGER;
for (let val of Object.values(mm)) {
result = Math.max(result, val);
}
return result;
}
function newNode(data) {
return new Node(data);
}
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);
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
Last Updated :
11 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...