Iterative method to check if two trees are mirror of each other
- Difficulty Level : Medium
- Last Updated : 17 Jun, 2022
Given two binary trees. The problem is to check whether the two binary trees are mirrors of each other or not.
Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.
Trees in the above figure are mirrors of each other.
We have discussed a recursive solution to check if two trees are mirror. In this post iterative solution is discussed.
Prerequisite: Iterative inorder tree traversal using stack
Approach: The following steps are:
- Perform iterative inorder traversal of one tree and iterative reverse inorder traversal of the other tree in parallel.
- During these two iterative traversals check that the corresponding nodes have the same value or not. If not same then they are not mirrors of each other.
- If values are same, then check whether at any point in the iterative inorder traversal one of the root becomes null and the other is not null. If this happens then they are not mirrors of each other. This check ensures whether they have the corresponding mirror structures or not.
- Otherwise, both the trees are mirror of each other.
Reverse inorder traversal is the opposite of inorder traversal. In this, the right subtree is traversed first, then root, and then the left subtree.
Time Complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. 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.