VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-two-trees-are-mirror/

⇱ Check if two trees are Mirror - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if two trees are Mirror

Last Updated : 23 Jul, 2025

Given two Binary Trees, the task is to check if two trees are mirror 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.

[Expected Approach - 1] Recursive Approach - O(n) Time and O(h) Space

The idea is to check if two binary trees are mirrors of each other by comparing their structure and node values. We recursively verify if the root nodes of both trees have the same value, then check if the left subtree is a mirror of the right subtree. If both trees are empty, they are considered mirrors; if one is empty and the other is not, they are not mirrors. This approach ensures that the trees are symmetric with respect to their root.

Below is implementation of above approach:


Output
true

Time Complexity:O(n), where n is the number of nodes in the trees.
Auxiliary Space: O(h), where h is height of binary tree.

[Expected Approach - 2] Iterative Approach - O(n) Time and O(n) Space

The idea is to check if two binary trees are mirrors using two stacks to simulate recursion. Nodes from each tree are pushed onto the stacks in a way that compares the left subtree of one tree with the right subtree of the other, and vice versa. This approach systematically compares nodes while maintaining their mirrored structure, ensuring the trees are symmetric relative to their root. Please refer to Iterative method to check if two trees are mirror of each other for implementation.

Comment