Skip to content
Related Articles

Related Articles

Check mirror in n-ary tree
  • Difficulty Level : Hard
  • Last Updated : 17 Feb, 2021

Given two n-ary trees, the task is to check if they are mirror of each other or not. Print “Yes” if they are 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

The idea is to use Queue and Stack to check if given N-ary tree are mirror of each other or not. 
Let first n-ary tree be t1 and second n-ary tree is t2. For each node in t1, make stack and push its connected node in it. Now, for each node in t2, make queue and push its connected node in it. 
Now, for each corresponding node do following:  

  While stack and Queue is not empty.
  a = top element of stack;
  b = front of queue;
  if (a != b)
    return false;
  pop element from stack and queue.

CPP




// C++ program to check if two n-ary trees are
// mirror.
#include <bits/stdc++.h>
using namespace std;
 
// First vector stores all nodes and adjacent of every
// node in a stack.
// Second vector stores all nodes and adjacent of every
// node in a queue.
bool mirrorUtil(vector<stack<int> >& tree1,
                      vector<queue<int> >& tree2)
{
    // Traversing each node in tree.
    for (int i = 1; i < tree1.size(); ++i) {
        stack<int>& s = tree1[i];
        queue<int>& q = tree2[i];
 
        // While stack is not empty && Queue is not empty
        while (!s.empty() && !q.empty()) {
 
            // checking top element of stack and front
            // of queue.
            if (s.top() != q.front())
                return false;
 
            s.pop();
            q.pop();
        }
 
        // If queue or stack is not empty, return false.
        if (!s.empty() || !q.empty())
            return false;
    }
 
    return true;
}
 
// Returns true if given two trees are mirrors.
// A tree is represented as two arrays to store
// all tree edges.
void areMirrors(int m, int n, int u1[], int v1[],
                            int u2[], int v2[])
{
    vector<stack<int> > tree1(m + 1);
    vector<queue<int> > tree2(m + 1);
 
    // Pushing node in the stack of first tree.
    for (int i = 0; i < n; i++)
        tree1[u1[i]].push(v1[i]);   
 
    // Pushing node in the queue of second tree.
    for (int i = 0; i < n; i++)
        tree2[u2[i]].push(v2[i]);
     
 
    mirrorUtil(tree1, tree2) ? (cout << "Yes" << endl) :
                               (cout << "No" << endl);
}
 
// Driver code
int main()
{
    int M = 3, N = 2;
 
    int u1[] = { 1, 1 };
    int v1[] = { 2, 3 };
 
    int u2[] = { 1, 1 };
    int v2[] = { 3, 2 };
 
    areMirrors(M, N, u1, v1, u2, v2);
 
    return 0;
}


Java




// Java program to check if two n-ary trees are
// mirror.
import java.util.*;
 
class GFG
{
  static Vector<Stack<Integer> > tree1;
  static Vector<Queue<Integer> > tree2;
 
  // First vector stores all nodes and adjacent of every
  // node in a stack.
  // Second vector stores all nodes and adjacent of every
  // node in a queue.
  static boolean mirrorUtil()
  {
 
    // Traversing each node in tree.
    for (int i = 1; i < tree1.size(); ++i)
    {
      Stack<Integer>s = tree1.get(i);
      Queue<Integer>q = tree2.get(i);
 
      // While stack is not empty && Queue is not empty
      while (!s.isEmpty() && !q.isEmpty())
      {
 
        // checking top element of stack and front
        // of queue.
        if (s.peek() != q.peek())
          return false;
        s.pop();
        q.remove();
      }
 
      // If queue or stack is not empty, return false.
      if (!s.isEmpty() || !q.isEmpty())
        return false;
    }
    return true;
  }
 
  // Returns true if given two trees are mirrors.
  // A tree is represented as two arrays to store
  // all tree edges.
  @SuppressWarnings("unlikely-arg-type")
  static void areMirrors(int m, int n, int u1[], int v1[],
                         int u2[], int v2[])
  {
    tree1 = new Vector<>();
    tree2  = new Vector<>();
 
    // Pushing node in the stack of first tree.
    for (int i = 0; i < n; i++)
    {
      Stack<Integer> st = new Stack<>();
      if(tree1.contains(u1[i]))
        st.addAll(tree1.get(u1[i]));
      st.push(v1[i]);
      tree1.add(st);
    }
 
    // Pushing node in the queue of second tree.
    for (int i = 0; i < n; i++)
    {
      Queue<Integer> st = new LinkedList<>();
      if(tree2.contains(u1[i]))
        st.addAll(tree2.get(u1[i]));
      st.add(v1[i]);
      tree2.add(st);
    }
    boolean ans = mirrorUtil();
    if(ans)
      System.out.print("Yes" +"\n");
    else
      System.out.print("No" +"\n");
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int M = 3, N = 2;
    int u1[] = { 1, 1 };
    int v1[] = { 2, 3 };
    int u2[] = { 1, 1 };
    int v2[] = { 3, 2 };
    areMirrors(M, N, u1, v1, u2, v2);
  }
}
 
// This code is contributed by gauravrajput1


Python3




# Pytho3 program to check if two n-ary trees are
# mirror.
  
# First vector stores all nodes and adjacent of every
# node in a stack.
# Second vector stores all nodes and adjacent of every
# node in a queue.
def mirrorUtil(tree1, tree2):
 
    # Traversing each node in tree.
    for i in range(1, len(tree1)):
     
        s = tree1[i];
        q = tree2[i];
  
        # While stack is not empty && Queue is not empty
        while (len(s) != 0 and len(q) != 0):
  
            # checking top element of stack and front
            # of queue.
            if (s[-1] != q[0]):
                return False;
  
            s.pop();
            q.pop(0);
  
        # If queue or stack is not empty, return false.
        if(len(s) != 0 or len(q) != 0):
            return False;
  
    return True;
 
# Returns true if given two trees are mirrors.
# A tree is represented as two arrays to store
# all tree edges.
def areMirrors(m, n, u1, v1, u2, v2):
 
    tree1=[[] for i in range(m + 1)];
    tree2=[[] for i in range(m + 1)]
  
    # Pushing node in the stack of first tree.
    for i in range(n):
 
        tree1[u1[i]].append(v1[i]);   
  
    # Pushing node in the queue of second tree.
    for i in range(n):
     
        tree2[u2[i]].append(v2[i]);
      
    if mirrorUtil(tree1, tree2):
        print('Yes')
    else:
        print('No')
  
# Driver code
if __name__=='__main__':
 
    M = 3
    N = 2;
  
    u1 = [ 1, 1 ]
    v1 = [ 2, 3 ]
  
    u2 = [ 1, 1 ]
    v2 = [ 3, 2 ]
  
    areMirrors(M, N, u1, v1, u2, v2);
  
# This code is contributed by rutvik_56


C#




// C# program to check if two n-ary trees are
// mirror.
using System;
using System.Collections.Generic;
 
public class GFG
{
  static List<Stack<int> > tree1;
  static List<Queue<int> > tree2;
 
  // First vector stores all nodes and adjacent of every
  // node in a stack.
  // Second vector stores all nodes and adjacent of every
  // node in a queue.
  static bool mirrorUtil()
  {
 
    // Traversing each node in tree.
    for (int i = 1; i < tree1.Count; ++i)
    {
      Stack<int>s = tree1[i];
      Queue<int>q = tree2[i];
 
      // While stack is not empty && Queue is not empty
      while (s.Count != 0 && q.Count != 0)
      {
 
        // checking top element of stack and front
        // of queue.
        if (s.Peek() != q.Peek())
          return false;
        s.Pop();
        q.Dequeue();
      }
 
      // If queue or stack is not empty, return false.
      if (s.Count != 0 || q.Count != 0)
        return false;
    }
    return true;
  }
 
  // Returns true if given two trees are mirrors.
  // A tree is represented as two arrays to store
  // all tree edges.
  static void areMirrors(int m, int n, int []u1, int []v1,
                         int []u2, int []v2)
  {
    tree1 = new List<Stack<int> >();
    tree2  = new List<Queue<int> >();
 
    // Pushing node in the stack of first tree.
    for (int i = 0; i < n - 2; i++)
        tree1[u1[i]].Push(v1[i]);   
 
    // Pushing node in the queue of second tree.
    for (int i = 0; i < n - 2; i++)
        tree2[u2[i]].Enqueue(v2[i]);
       
      bool ans = mirrorUtil();
    if(ans)
      Console.Write("Yes" + "\n");
    else
      Console.Write("No" + "\n");
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int M = 3, N = 2;
    int []u1 = { 1, 1 };
    int []v1 = { 2, 3 };
    int []u2 = { 1, 1 };
    int []v2 = { 3, 2 };
    areMirrors(M, N, u1, v1, u2, v2);
  }
}
 
// This code is contributed by gauravrajput1


Output

Yes

Reference: https://practice.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree/0
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :