VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iterative-method-check-two-trees-mirror/

⇱ Iterative method to check if two trees are mirror of each other - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:  

  1. Their root node’s key must be same
  2. Left subtree of root of β€˜a’ and right subtree root of β€˜b’ are mirror.
  3. Right subtree of β€˜a’ and left subtree of β€˜b’ are mirror.

Example:

Input:

πŸ‘ Two-Mirror-Trees-1

Output: True
Explanation: Both trees are mirror images of each other, so output is True.

Input:

πŸ‘ Two-Mirror-Trees-2

Output: False
Explanation: Since both trees are not mirror images of each other, the output is False.


Approach:

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)

Please refer to Check if two trees are Mirror to solve using recursion.

Comment
Article Tags: