Given a Binary Tree having positive and negative nodes, the task is to find the maximum absolute difference of level sum in it.
Examples:
Input:
4
/ \
2 -5
/ \ / \
-1 3 -2 6
Output: 9
Explanation:
Sum of all nodes of 0 level is 4
Sum of all nodes of 1 level is -3
Sum of all nodes of 2 level is 6
Hence maximum absolute difference
of level sum = 9 (6 - (-3))
Input:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output: 16
Approach: To find the maximum absolute difference of level sum, we only need to find Maximum level sum and Minimum level sum because the absolute difference of maximum and minimum level sum always gives us Maximum absolute difference, i.e.
Maximum absolute difference = abs(Maximum level sum – Minimum level sum)
Below are the steps for the algorithm of the above observation:
- The idea is to do 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 maximum and minimum level sum.
- Then return the absolute difference of maximum and minimum level sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
Node *newNode( int data)
{
Node *node = new Node();
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int maxAbsDiffLevelSum(Node *root)
{
int maxsum = INT_MIN;
int minsum = INT_MAX;
queue<Node *> qu;
qu.push(root);
while (!qu.empty())
{
int sz = qu.size();
int sum = 0;
for ( int i = 0; i < sz; i++)
{
Node *t = qu.front();
qu.pop();
sum += t->data;
if (t->left != NULL)
qu.push(t->left);
if (t->right != NULL)
qu.push(t->right);
}
maxsum = max(maxsum, sum);
minsum = min(minsum, sum);
}
return abs (maxsum - minsum);
}
int main()
{
Node *root = new Node();
root = newNode(4);
root->left = newNode(2);
root->right = newNode(-5);
root->left->left = newNode(-1);
root->left->right = newNode(3);
root->right->left = newNode(-2);
root->right->right = newNode(6);
cout << maxAbsDiffLevelSum(root) << endl;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree {
Node root;
public BinaryTree()
{
root = null ;
}
public int maxAbsDiffLevelSum()
{
int maxsum = Integer.MIN_VALUE;
int minsum = Integer.MAX_VALUE;
Queue<Node> qu = new LinkedList<>();
qu.offer(root);
while (!qu.isEmpty()) {
int sz = qu.size();
int sum = 0 ;
for ( int i = 0 ; i < sz; i++) {
Node t = qu.poll();
sum += t.data;
if (t.left != null )
qu.offer(t.left);
if (t.right != null )
qu.offer(t.right);
}
maxsum = Math.max(maxsum, sum);
minsum = Math.min(minsum, sum);
}
return Math.abs(maxsum - minsum);
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 4 );
tree.root.left = new Node( 2 );
tree.root.right = new Node(- 5 );
tree.root.left.left = new Node(- 1 );
tree.root.left.right = new Node( 3 );
tree.root.right.left = new Node(- 2 );
tree.root.right.right = new Node( 6 );
System.out.println(
tree.maxAbsDiffLevelSum());
}
}
|
Python3
import sys
class newNode:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def maxAbsDiffLevelSum(root):
maxsum = - sys.maxsize - 1
minsum = sys.maxsize
qu = []
qu.append(root)
while ( len (qu) > 0 ):
sz = len (qu)
sum = 0
for i in range (sz):
t = qu[ 0 ]
qu.remove(qu[ 0 ])
sum + = t.data
if (t.left ! = None ):
qu.append(t.left)
if (t.right ! = None ):
qu.append(t.right)
maxsum = max (maxsum, sum )
minsum = min (minsum, sum )
return abs (maxsum - minsum)
if __name__ = = '__main__' :
root = newNode( 4 )
root.left = newNode( 2 )
root.right = newNode( - 5 )
root.left.left = newNode( - 1 )
root.left.right = newNode( 3 )
root.right.left = newNode( - 2 )
root.right.right = newNode( 6 )
print (maxAbsDiffLevelSum(root))
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = null ;
right = null ;
}
}
class BinaryTree{
Node root;
public int maxAbsDiffLevelSum()
{
int maxsum = Int32.MinValue;
int minsum = Int32.MaxValue;
Queue<Node> qu = new Queue<Node>();
qu.Enqueue(root);
while (qu.Count != 0)
{
int sz = qu.Count;
int sum = 0;
for ( int i = 0; i < sz; i++)
{
Node t = qu.Dequeue();
sum += t.data;
if (t.left != null )
qu.Enqueue(t.left);
if (t.right != null )
qu.Enqueue(t.right);
}
maxsum = Math.Max(maxsum, sum);
minsum = Math.Min(minsum, sum);
}
return Math.Abs(maxsum - minsum);
}
static public void Main ()
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(4);
tree.root.left = new Node(2);
tree.root.right = new Node(-5);
tree.root.left.left = new Node(-1);
tree.root.left.right = new Node(3);
tree.root.right.left = new Node(-2);
tree.root.right.right = new Node(6);
Console.WriteLine(tree.maxAbsDiffLevelSum());
}
}
|
Javascript
<script>
class Node
{
constructor(item) {
this .left = null ;
this .right = null ;
this .data = item;
}
}
let root;
function maxAbsDiffLevelSum()
{
let maxsum = Number.MIN_VALUE;
let minsum = Number.MAX_VALUE;
let qu = [];
qu.push(root);
while (qu.length != 0)
{
let sz = qu.length;
let sum = 0;
for (let i = 0; i < sz; i++)
{
let t = qu.shift();
sum += t.data;
if (t.left != null )
qu.push(t.left);
if (t.right != null )
qu.push(t.right);
}
maxsum = Math.max(maxsum, sum);
minsum = Math.min(minsum, sum);
}
return Math.abs(maxsum - minsum);
}
root = new Node(4);
root.left = new Node(2);
root.right = new Node(-5);
root.left.left = new Node(-1);
root.left.right = new Node(3);
root.right.left = new Node(-2);
root.right.right = new Node(6);
document.write(maxAbsDiffLevelSum());
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
22 Jun, 2021
Like Article
Save Article