Maximum Absolute difference between any two Level Sum in a Binary Tree


In this problem, we will find the maximum absolute difference between the sum of all nodes of any two levels.

We can use the queue data structure to traverse through each binary tree level. While traversing each level, we can keep track of the maximum and minimum sum and return the absolute difference at last.

Problem statement − We have given a binary tree containing the positive and negative integer values. We need to find the maximum absolute difference of the sum of all nodes of any two levels.

Sample examples

Input

                  
                  300
	            /     \
	           5       7
 	         /   \     /
	        1     1    1

Output

297

Explanation − The sum of the first level is 300, and the last level is 3. So, the maximum difference is 297.

Input

                   
                       10
	              /  \
	             -9  -8
 	             / \  /
	           10   6 11

Output

44

Explanation − The sum of the last level is 27, and the second level is −17. So, the absolute difference is 27 − (−17) is 44.

Input

                  
                  -50
	             /   \
	            19   -21
 	           /  \  /  \
	         -12   9 21  -20

Output

48

Explanation − The sum of the first level is −50, and the second level is −2. So, −50 − (−2) is 48.

Approach

In this approach, we will use the level order traversal. We will take the sum of all nodes of each level while traversing through each level. Also, we will store the maximum and minimum level sum. At last, we will take its absolute difference and return it as an answer.

Algorithm

Step 1 − Define the TreeNode class to create nodes for the binary tree. The TreeNode class contains the ‘val’ integer value, ‘left’, and ‘right’ pointers. Also, it contains the constructor to initialize the new node for the binary tree.

Step 2 − Now, define the max_sum and initialize with the minimum integer value to store the maximum sum. Also, define the min_sum and initialize it with the maximum integer value to store the minimum sum.

Step 3 − Define the queue and insert the root node of the tree into the queue.

Step 4 − Use the while loop and make iterations until the queue contains at least a single node.

Step 4.1 − Initialize the ‘sum’ with 0 to store the sum of the current level.

Step 4.2 − Start traversing the queue elements using the nested for loop.

Step 4.2.1 − Pop the first queue element, and add its value to the sum variable.

Step 4.2.2 − If the left of the left node is not null, insert it into the queue. Also, insert the right node of the ‘temp’ is not null, insert it into the queue.

Step 4.3 − Update the max_sum and min_sum value if the current sum is maximum than the max_sum or minimum than the min_sum.

Step 5 − At last, return the absolute difference between max_sum and min_sum.

Example

#include <bits/stdc++.h>
using namespace std;

class TreeNode {
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val) {
        this->val = val;
        left = NULL;
        right = NULL;
    }
};
int maxAbsDiff(TreeNode *head) {
    int max_sum = INT_MIN;
    int min_sum = INT_MAX;
    queue<TreeNode *> que;
    que.push(head);
    // BFS
    while (!que.empty()) {
        int temp_size = que.size();
        // Initial sum is 0.
        int sum = 0;
        for (int p = 0; p < temp_size; p++) {
            TreeNode *temp = que.front();
            que.pop();
            // Add value to the sum
            sum += temp->val;
            // Insert the left and right node of the current node to queue
            if (temp->left != NULL)
                que.push(temp->left);

            if (temp->right != NULL)
                que.push(temp->right);
        }
        max_sum = max(max_sum, sum);
        min_sum = min(min_sum, sum);
    }
    // Get difference
    return abs(max_sum - min_sum);
}
int main() {
    TreeNode *head = new TreeNode(300);
    head->left = new TreeNode(5);
    head->right = new TreeNode(7);
    head->left->left = new TreeNode(1);
    head->left->right = new TreeNode(1);
    head->right->left = new TreeNode(1);
    cout << "The maximum absolute difference between the sum of two levels of binary tree is " << maxAbsDiff(head) << endl;
}

Output

The maximum absolute difference between the sum of two levels of binary tree is 297

Time complexity − O(N) to visit all nodes.

Space complexity − O(N) to store nodes in the queue.

We used the BFS and level order traversal to traverse each through each level and get a sum of each level.

Updated on: 02-Aug-2023

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements