Skip to content
Related Articles

Related Articles

Improve Article

Check mirror in n-ary tree

  • Difficulty Level : Hard
  • Last Updated : 30 Jun, 2021

Given two n-ary trees, the task is to check if they are the mirror of each other or not. Print “Yes” if they are the mirror of each other else “No”.

Examples: 

Input : Node = 3, Edges = 2
Edge 1 of first N-ary: 1 2
Edge 2 of first N-ary: 1 3
Edge 1 of second N-ary: 1 3
Edge 2 of second N-ary: 1 2
Output : Yes

Input : Node = 3, Edges = 2
Edge 1 of first N-ary: 1 2 
Edge 2 of first N-ary: 1 3
Edge 1 of second N-ary: 1 2
Edge 2 of second N-ary: 1 3
Output : No

Approach  1: (Using Hashing)

The idea is to use an unordered map of stacks to check if given N-ary tree are mirror of each other or not. 
Let the first n-ary tree be t1 and the second n-ary tree is t2. For each node in t1, push its connected node in their corresponding stack in the map. Now, for each node in t2, their connected node match with the top of the stack, then pop elements from the stack.  



Otherwise, if the node does not match with the top of the stack then it means two trees are not mirror of each other. 
Now, for each corresponding node do the following:  

  1. Iterate over map of stack
      Push all connected nodes of each node of first tree in map of  stack.

  2. Again iterate over map for each node of second tree
      For example :     

      Let us take one node X of second tree 
      
      For this node X , check in map which stack is used

      a = Top of that stack for node X present in second tree;
      b = Connected node of X in second tree
      if (a != b)
           return false;
      pop node X from stack.

C++




// C++ program to check if two n-ary trees are
// mirror.
#include <bits/stdc++.h>
using namespace std;
 
// Function to check given two trees are mirror
// of each other or not
int checkMirrorTree(int M, int N, int u1[ ],
                    int v1[ ] , int u2[], int v2[])
    {
        // Map to store nodes of the tree
        unordered_map<int , stack<int>>mp;
   
        // Traverse first tree nodes
        for (int i = 0 ; i < N ; i++ )
        {
           mp[u1[i]].push(v1[i]);
        }
         
        // Traverse second tree nodes
        for (int i = 0 ; i < N ; i++)
        {
            if(mp[u2[i]].top() != v2[i])
                  return 0;
            mp[u2[i]].pop();
        }
   
        return 1;
    }
 
// Driver code
int main()
{
    int M = 7, N = 6;
     
    //Tree 1
    int u1[] = { 1, 1, 1, 10, 10, 10 };
    int v1[] = { 10, 7, 3, 4, 5, 6 };
   
    //Tree 2
    int u2[] = { 1, 1, 1, 10, 10, 10 };
    int v2[] = { 3, 7, 10, 6, 5, 4 };
 
    if(checkMirrorTree(M, N, u1, v1, u2, v2))
       cout<<"Yes";
    else
       cout<<"No";
   
    return 0;
}
Output
Yes

Approach 2: (Using LinkedList):

The main approach is to use one list of stack and one list of queue to store to value of nodes given in the form of two arrays.

1. Initialize both the lists with empty stack and empty queues respectively.

2. Now, iterate over the lists
    Push all connected nodes of each node of first tree in list of stack and second tree list of queue.
    
3. Now iterate over the array and pop item from both stack and queue and check if they are same, if not same then return 0.

Java




// Java program to check two n-ary trees are mirror.
 
import java.io.*;
import java.util.*;
 
class GFG {
   
      // Function to check given two trees are mirror
    // of each other or not
      static int checkMirrorTree(int n, int e, int[] A, int[] B) {
 
          //Lists to store nodes of the tree
        List<Stack<Integer>> s = new ArrayList<>();
        List<Queue<Integer>> q = new ArrayList<>();
 
        // initializing both list with empty stack and queue
        for (int i = 0; i <= n; i++) {
            s.add(new Stack<>());
            Queue<Integer> queue = new LinkedList<>();
            q.add(queue);
        }
 
           // add all nodes of tree 1 to list of stack and tree 2 to list of queue
        for (int i = 0; i < 2 * e; i += 2) {
            s.get(A[i]).push(A[i + 1]);
            q.get(B[i]).add(B[i + 1]);
        }
 
          // now take out the stack and queues
        // for each of the nodes and compare them
        // one by one
        for (int i = 1; i <= n; i++) {
            while (!s.get(i).isEmpty() && !q.get(i).isEmpty()) {
                int a = s.get(i).pop();
                int b = q.get(i).poll();
 
                if (a != b) {
                    return 0;
                }
            }
        }
 
        return 1;
    }
   
    public static void main (String[] args) {
        int n = 3;
        int e = 2;
        int A[] = { 1, 2, 1, 3 };
        int B[] = { 1, 3, 1, 2 };
 
        if (checkMirrorTree(n, e, A, B) == 1) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
 
    }
}

Javascript




<script>
    // Javascript program to check two n-ary trees are mirror.
     
    // Function to check given two trees are mirror
    // of each other or not
      function checkMirrorTree(n, e, A, B) {
  
          //Lists to store nodes of the tree
        let s = [];
        let q = [];
  
        // initializing both list with empty stack and queue
        for (let i = 0; i <= n; i++) {
            s.push([]);
            let queue = [];
            q.push(queue);
        }
  
           // add all nodes of tree 1 to
           // list of stack and tree 2 to list of queue
        for (let i = 0; i < 2 * e; i += 2) {
            s[A[i]].push(A[i + 1]);
            q[B[i]].push(B[i + 1]);
        }
  
          // now take out the stack and queues
        // for each of the nodes and compare them
        // one by one
        for (let i = 1; i <= n; i++) {
            while (s[i].length > 0 && q[i].length > 0) {
                let a = s[i][s[i].length - 1];
                s[i].pop();
                let b = q[i][0];
                q[i].shift();
  
                if (a != b) {
                    return 0;
                }
            }
        }
  
        return 1;
    }
     
    let n = 3;
    let e = 2;
    let A = [ 1, 2, 1, 3 ];
    let B = [ 1, 3, 1, 2 ];
 
    if (checkMirrorTree(n, e, A, B) == 1) {
      document.write("Yes");
    } else {
      document.write("No");
    }
    
   // This code is contributed by suresh07.
</script>
Output
Yes

Reference: https://practice.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree/0
This article is contributed by Nitin Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :