Find mirror of a given node in Binary tree
- Difficulty Level : Hard
- Last Updated : 13 Jul, 2022
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.