Iterative method to check if two trees are mirror of each other
Last Updated : 23 Jul, 2025
Given two Binary Trees, the task is to check if two trees are mirrors of each other or not. For two trees βaβ and βbβ to be mirror images, the following three conditions must be true:
Their root nodeβs key must be same
Left subtree of root of βaβ and right subtree root of βbβ are mirror.
Right subtree of βaβ and left subtree of βbβ are mirror.
The idea is to check if two binary trees are mirrors using two stacks to simulate the recursive process. Nodes from each tree are pushed onto the stacks in a manner that compares the left subtree of one tree with the right subtree of the other, and vice versa. By systematically comparing nodes from both trees while maintaining their mirrored structure in the stacks, the approach ensures that the trees are symmetric relative to their root.
Step-by-step implementation:
If both root1 and root2 are null, return true because two empty trees are mirrors of each other.
If one tree is null while the other isn't, return false, as they can't be mirrors.
Create two stacks, stk1 and stk2, to store nodes for simultaneous iterative traversal of both trees.
Pop nodes from both stacks, compare their data, and check if the current nodes have left and right children in a mirrored fashion (left of root1 with right of root2 and vice versa).
If the current node pairs have corresponding children, push them onto the stacks; otherwise, return false if the structure is not symmetric.
After traversal, if both stacks are empty, return true; otherwise, return false.
Below is implementation of above approach:
Output
true
Time Complexity: O(n), because we are visiting each node once, where n is the number of nodes in the trees. Auxiliary Space: O(n)