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:
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.
[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.