Find mirror of a given node in Binary tree
Given a Binary tree, the problem is to find the mirror of a given node. The mirror of a node is a node which exists at the mirror position of the node in opposite subtree at the root.
In above tree- Node 2 and 3 are mirror nodes Node 4 and 6 are mirror nodes.
We can have a recursive solution for finding mirror nodes. The algorithm is following –
1) Start from the root of the tree and recur nodes from both subtree simultaneously using two pointers for left and right nodes. 2) First recur all the external nodes and store returned value in mirror variable. 3) If current node value is equal to target node, return the value of opposite pointer else repeat step 2. 4) If no external node is left and mirror is none, recur internal nodes.
Mirror of node 4 is node 6
This article is contributed by Atul 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.