Open In App

Find the Absolute Difference between the Right View Sum of two Binary Trees

Given two binary trees, the task is to find the sum of the absolute differences between the right view of binary trees.

Examples:



Input: Tree 1:

10
/ \
5 20
/ \ \
4 7 30



Tree 2:

50
/ \
25 60
/ \ / \
20 30 55 70

Output: 120
Explanation: For Tree 1, the right view nodes are 10, 20, and 30. Therefore, the right view sum is 10 + 20 + 30 = 60, and For Tree 2, the right view nodes are 50, 60, and 70. Therefore, the right view sum is 50 + 60 + 70 = 180. The absolute difference between the right view sum of Tree 1 and Tree 2 is |180 – 60| = 120. Therefore, the output is 120.

Input: Tree 1:

1
/ \
2 3
/ \ / \
4 5 6 7

Tree 2:

6
/ \
7 5
/ \ / \
1 5 4 3

Output: 3
Explanation: Right view sum of Tree 1: 1 + 3 + 7 = 11, Right view sum of Tree 2: 6 + 5 + 3 = 14. Thus |14 – 11| = 3

Approach: To solve the problem follow the below idea:

This problem requires us to calculate the sum of nodes that are visible from the right side of the binary tree and then find the absolute difference between the sums of the right view of two given binary trees. To calculate the sum of nodes that are visible from the right side of the binary tree, we can do a level-order traversal of the binary tree and for each level, we can add the rightmost node’s value to the sum. We can use a queue to perform the level-order traversal of the binary tree. We first push the root node into the queue and then continue to process nodes until the queue becomes empty. For each level of the binary tree, we set a flag to indicate that the next node to be processed is the rightmost node. Then we pop each node from the queue and add its value to the sum if the flag is set. We then push its right and left child nodes into the queue if they exist. If we have processed all the nodes in a level, we reset the flag to indicate that the next node to be processed is the rightmost node of the next level. Once we have calculated the right view sum of both binary trees, we can find the absolute difference between them and return the result.

Steps of the approach:

Implementation of the above approach:




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Function to create a new node
// with the given data
Node* createNode(int data)
{
    Node* newNode = new Node;
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}
 
// Function to calculate the absolute difference
// of right view sums for two binary trees
int absoluteDifference(Node* root1, Node* root2)
{
    // Check if either of the input roots is
    // NULL, indicating invalid input
    if (root1 == NULL || root2 == NULL) {
 
        // Invalid input, return -1 or any
        // suitable value
        return -1;
    }
 
    int sum1 = 0;
    int sum2 = 0;
 
    // Create two queues for level-order
    // traversal of the two trees
    queue<Node*> q1, q2;
    q1.push(root1);
    q2.push(root2);
 
    while (!q1.empty() || !q2.empty()) {
        int size1 = q1.size();
        int size2 = q2.size();
 
        // Process nodes at the same
        // level in both trees
        while (size1--) {
            Node* curr = q1.front();
            q1.pop();
            // If it's the rightmost element in
            // the level, update sum1
            if (size1 == 0) {
                sum1 += curr->data;
            }
            // Add left and right children to
            // the queue for further traversal
            if (curr->left) {
                q1.push(curr->left);
            }
            if (curr->right) {
                q1.push(curr->right);
            }
        }
 
        while (size2--) {
            Node* curr = q2.front();
            q2.pop();
            // If it's the rightmost element in
            // the level, update sum2
            if (size2 == 0) {
                sum2 += curr->data;
            }
            // Add left and right children to
            // the queue for further traversal
            if (curr->left) {
                q2.push(curr->left);
            }
            if (curr->right) {
                q2.push(curr->right);
            }
        }
    }
 
    // Calculate and return the
    // absolute difference
    return abs(sum1 - sum2);
}
 
// Drivers code
int main()
{
    // Create the first binary tree (root1)
    Node* root1 = createNode(10);
    root1->left = createNode(5);
    root1->right = createNode(20);
    root1->left->left = createNode(4);
    root1->left->right = createNode(7);
    root1->right->right = createNode(30);
 
    // Create the second binary tree (root2)
    Node* root2 = createNode(50);
    root2->left = createNode(25);
    root2->right = createNode(60);
    root2->left->left = createNode(20);
    root2->left->right = createNode(30);
    root2->right->left = createNode(55);
    root2->right->right = createNode(70);
 
    // Calculate the absolute difference
    // of right view sums
    int diff = absoluteDifference(root1, root2);
 
    // Print the result
    cout << "Absolute Difference of Right View Sums: "
         << diff << endl;
 
    return 0;
}




import java.util.LinkedList;
import java.util.Queue;
 
class Node {
    int data;
    Node left, right;
 
    Node(int item) {
        data = item;
        left = right = null;
    }
}
 
public class BinaryTreeDifference {
 
    // Function to calculate the absolute difference
    // of right view sums for two binary trees
    static int absoluteDifference(Node root1, Node root2) {
        // Check if either of the input roots is
        // NULL, indicating invalid input
        if (root1 == null || root2 == null) {
            // Invalid input, return -1 or any
            // suitable value
            return -1;
        }
 
        int sum1 = 0;
        int sum2 = 0;
 
        // Create two queues for level-order
        // traversal of the two trees
        Queue<Node> q1 = new LinkedList<>();
        Queue<Node> q2 = new LinkedList<>();
        q1.add(root1);
        q2.add(root2);
 
        while (!q1.isEmpty() || !q2.isEmpty()) {
            int size1 = q1.size();
            int size2 = q2.size();
 
            // Process nodes at the same
            // level in both trees
            while (size1-- > 0) {
                Node curr = q1.poll();
                // If it's the rightmost element in
                // the level, update sum1
                if (size1 == 0) {
                    sum1 += curr.data;
                }
                // Add left and right children to
                // the queue for further traversal
                if (curr.left != null) {
                    q1.add(curr.left);
                }
                if (curr.right != null) {
                    q1.add(curr.right);
                }
            }
 
            while (size2-- > 0) {
                Node curr = q2.poll();
                // If it's the rightmost element in
                // the level, update sum2
                if (size2 == 0) {
                    sum2 += curr.data;
                }
                // Add left and right children to
                // the queue for further traversal
                if (curr.left != null) {
                    q2.add(curr.left);
                }
                if (curr.right != null) {
                    q2.add(curr.right);
                }
            }
        }
 
        // Calculate and return the
        // absolute difference
        return Math.abs(sum1 - sum2);
    }
 
    // Drivers code
    public static void main(String[] args) {
        // Create the first binary tree (root1)
        Node root1 = new Node(10);
        root1.left = new Node(5);
        root1.right = new Node(20);
        root1.left.left = new Node(4);
        root1.left.right = new Node(7);
        root1.right.right = new Node(30);
 
        // Create the second binary tree (root2)
        Node root2 = new Node(50);
        root2.left = new Node(25);
        root2.right = new Node(60);
        root2.left.left = new Node(20);
        root2.left.right = new Node(30);
        root2.right.left = new Node(55);
        root2.right.right = new Node(70);
 
        // Calculate the absolute difference
        // of right view sums
        int diff = absoluteDifference(root1, root2);
 
        // Print the result
        System.out.println("Absolute Difference of Right View Sums: " + diff);
    }
}




from queue import Queue
 
class Node:
    def __init__(self, item):
        self.data = item
        self.left = self.right = None
 
def absolute_difference(root1, root2):
    if root1 is None or root2 is None:
        return -1
 
    sum1, sum2 = 0, 0
 
    q1 = Queue()
    q2 = Queue()
    q1.put(root1)
    q2.put(root2)
 
    while not q1.empty() or not q2.empty():
        size1 = q1.qsize()
        size2 = q2.qsize()
 
        while size1 > 0:
            curr = q1.get()
            if size1 == 1:
                sum1 += curr.data
            if curr.left:
                q1.put(curr.left)
            if curr.right:
                q1.put(curr.right)
            size1 -= 1
 
        while size2 > 0:
            curr = q2.get()
            if size2 == 1:
                sum2 += curr.data
            if curr.left:
                q2.put(curr.left)
            if curr.right:
                q2.put(curr.right)
            size2 -= 1
 
    return abs(sum1 - sum2)
 
# Driver code
if __name__ == "__main__":
    # Create the first binary tree (root1)
    root1 = Node(10)
    root1.left = Node(5)
    root1.right = Node(20)
    root1.left.left = Node(4)
    root1.left.right = Node(7)
    root1.right.right = Node(30)
 
    # Create the second binary tree (root2)
    root2 = Node(50)
    root2.left = Node(25)
    root2.right = Node(60)
    root2.left.left = Node(20)
    root2.left.right = Node(30)
    root2.right.left = Node(55)
    root2.right.right = Node(70)
 
    # Calculate the absolute difference of right view sums
    diff = absolute_difference(root1, root2)
 
    # Print the result
    print("Absolute Difference of Right View Sums:", diff)
 
 # code is contributed by shinjanpatra




using System;
using System.Collections.Generic;
 
public class Node
{
    public int data;
    public Node left, right;
 
    // Constructor to create a new node
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class BinaryTree
{
    // Function to calculate the absolute difference
    // of right view sums for two binary trees
    public static int AbsoluteDifference(Node root1, Node root2)
    {
        // Check if either of the input roots is
        // NULL, indicating invalid input
        if (root1 == null || root2 == null)
        {
            // Invalid input, return -1 or any
            // suitable value
            return -1;
        }
 
        int sum1 = 0;
        int sum2 = 0;
 
        // Create two queues for level-order
        // traversal of the two trees
        Queue<Node> q1 = new Queue<Node>();
        Queue<Node> q2 = new Queue<Node>();
        q1.Enqueue(root1);
        q2.Enqueue(root2);
 
        while (q1.Count > 0 || q2.Count > 0)
        {
            int size1 = q1.Count;
            int size2 = q2.Count;
 
            // Process nodes at the same
            // level in both trees
            while (size1 > 0)
            {
                Node curr = q1.Dequeue();
                // If it's the rightmost element in
                // the level, update sum1
                if (size1 == 1)
                {
                    sum1 += curr.data;
                }
                // Add left and right children to
                // the queue for further traversal
                if (curr.left != null)
                {
                    q1.Enqueue(curr.left);
                }
                if (curr.right != null)
                {
                    q1.Enqueue(curr.right);
                }
                size1--;
            }
 
            while (size2 > 0)
            {
                Node curr = q2.Dequeue();
                // If it's the rightmost element in
                // the level, update sum2
                if (size2 == 1)
                {
                    sum2 += curr.data;
                }
                // Add left and right children to
                // the queue for further traversal
                if (curr.left != null)
                {
                    q2.Enqueue(curr.left);
                }
                if (curr.right != null)
                {
                    q2.Enqueue(curr.right);
                }
                size2--;
            }
        }
 
        // Calculate and return the
        // absolute difference
        return Math.Abs(sum1 - sum2);
    }
 
    // Drivers code
    public static void Main(string[] args)
    {
        // Create the first binary tree (root1)
        Node root1 = new Node(10);
        root1.left = new Node(5);
        root1.right = new Node(20);
        root1.left.left = new Node(4);
        root1.left.right = new Node(7);
        root1.right.right = new Node(30);
 
        // Create the second binary tree (root2)
        Node root2 = new Node(50);
        root2.left = new Node(25);
        root2.right = new Node(60);
        root2.left.left = new Node(20);
        root2.left.right = new Node(30);
        root2.right.left = new Node(55);
        root2.right.right = new Node(70);
 
        // Calculate the absolute difference
        // of right view sums
        int diff = AbsoluteDifference(root1, root2);
 
        // Print the result
        Console.WriteLine("Absolute Difference of Right View Sums: " + diff);
    }
}




class Node {
  constructor(item) {
    this.data = item;
    this.left = this.right = null;
  }
}
 
function absoluteDifference(root1, root2) {
  if (!root1 || !root2) {
    return -1;
  }
 
  let sum1 = 0,
    sum2 = 0;
  let queue1 = [],
    queue2 = [];
 
  queue1.push(root1);
  queue2.push(root2);
 
  while (queue1.length > 0 || queue2.length > 0) {
    let size1 = queue1.length;
    let size2 = queue2.length;
 
    while (size1 > 0) {
      let curr = queue1.shift();
      if (size1 === 1) {
        sum1 += curr.data;
      }
      if (curr.left) {
        queue1.push(curr.left);
      }
      if (curr.right) {
        queue1.push(curr.right);
      }
      size1 -= 1;
    }
 
    while (size2 > 0) {
      let curr = queue2.shift();
      if (size2 === 1) {
        sum2 += curr.data;
      }
      if (curr.left) {
        queue2.push(curr.left);
      }
      if (curr.right) {
        queue2.push(curr.right);
      }
      size2 -= 1;
    }
  }
 
  return Math.abs(sum1 - sum2);
}
 
// Driver code
// Create the first binary tree (root1)
let root1 = new Node(10);
root1.left = new Node(5);
root1.right = new Node(20);
root1.left.left = new Node(4);
root1.left.right = new Node(7);
root1.right.right = new Node(30);
 
// Create the second binary tree (root2)
let root2 = new Node(50);
root2.left = new Node(25);
root2.right = new Node(60);
root2.left.left = new Node(20);
root2.left.right = new Node(30);
root2.right.left = new Node(55);
root2.right.right = new Node(70);
 
// Calculate the absolute difference of right view sums
let diff = absoluteDifference(root1, root2);
 
// Print the result
console.log("Absolute Difference of Right View Sums:", diff);

Output
Absolute Difference of Right View Sums: 120













Time Complexity: O(N), where N is the total number of nodes in both trees.
Auxiliary Space: O(N)


Article Tags :