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”.
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 : (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.
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 email@example.com. 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 industry experts, please refer Geeks Classes Live