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”.
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 : 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.
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 firstname.lastname@example.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.