Check if two trees are Mirror - GeeksforGeeks

30 Aug, 2021
Given two Binary Trees, write a function that returns true if two trees are mirror of each other, else false. For example, the function should return true for following input trees. 
 
This problem is different from the problem discussed here.For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true:  
Their root node’s key must be sameLeft subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.Right subtree of ‘a’ and left subtree of ‘b’ are mirror.
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.
Below is implementation of above idea.  
C++
Java
Python3
C#
Javascript
// C++ program to check if two trees are mirror// of each other#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to   left child and a pointer to right child */struct Node{    int data;    Node* left, *right;}; /* Given two trees, return true if they are   mirror of each other *//*As function has to return bool value instead integer value*/bool areMirror(Node* a, Node* b){    /* Base case : Both empty */    if (a==NULL && b==NULL)        return true;     // If only one is empty    if (a==NULL || b == NULL)        return false;     /* Both non-empty, compare them recursively     Note that in recursive calls, we pass left     of one tree and right of other tree */    return  a->data == b->data &&            areMirror(a->left, b->right) &&            areMirror(a->right, b->left);} /* Helper function that allocates a new node */Node* newNode(int data){    Node* node = new Node;    node->data  = data;    node->left  =  node->right  = NULL;    return(node);} /* Driver program to test areMirror() */int main(){    Node *a = newNode(1);    Node *b = newNode(1);    a->left = newNode(2);    a->right = newNode(3);    a->left->left  = newNode(4);    a->left->right = newNode(5);     b->left = newNode(3);    b->right = newNode(2);    b->right->left = newNode(5);    b->right->right = newNode(4);     areMirror(a, b)? cout << "Yes" : cout << "No";     return 0;}
// Java program to see if two trees// are mirror of each other // A binary tree nodeclass Node{    int data;    Node left, right;     public Node(int data)    {        this.data = data;        left = right = null;    }} class BinaryTree{    Node a, b;         /* Given two trees, return true if they are       mirror of each other */    boolean areMirror(Node a, Node b)    {        /* Base case : Both empty */        if (a == null && b == null)            return true;         // If only one is empty        if (a == null || b == null)            return false;         /* Both non-empty, compare them recursively           Note that in recursive calls, we pass left           of one tree and right of other tree */        return a.data == b.data                && areMirror(a.left, b.right)                && areMirror(a.right, b.left);    }     // Driver code to test above methods    public static void main(String[] args)    {        BinaryTree tree = new BinaryTree();        Node a = new Node(1);        Node b = new Node(1);        a.left = new Node(2);        a.right = new Node(3);        a.left.left = new Node(4);        a.left.right = new Node(5);         b.left = new Node(3);        b.right = new Node(2);        b.right.left = new Node(5);        b.right.right = new Node(4);         if (tree.areMirror(a, b) == true)            System.out.println("Yes");        else            System.out.println("No");     }} // This code has been contributed by Mayank Jaiswal(mayank_24)
# Python3 program to check if two# trees are mirror of each other # A binary tree nodeclass Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = None # Given two trees, return true# if they are mirror of each otherdef areMirror(a, b):         # Base case : Both empty    if a is None and b is None:        return True         # If only one is empty    if a is None or b is None:        return False         # Both non-empty, compare them    # recursively. Note that in    # recursive calls, we pass left    # of one tree and right of other tree    return (a.data == b.data and            areMirror(a.left, b.right) and            areMirror(a.right , b.left)) # Driver coderoot1 = Node(1)root2 = Node(1) root1.left = Node(2)root1.right = Node(3)root1.left.left = Node(4)root1.left.right = Node(5) root2.left = Node(3)root2.right = Node(2)root2.right.left = Node(5)root2.right.right = Node(4) if areMirror(root1, root2):    print ("Yes")else:    print ("No") # This code is contributed by AshishR
using System; // c# program to see if two trees// are mirror of each other // A binary tree nodepublic class Node{    public int data;    public Node left, right;     public Node(int data)    {        this.data = data;        left = right = null;    }} public class BinaryTree{    public Node a, b;     /* Given two trees, return true if they are    mirror of each other */    public virtual bool areMirror(Node a, Node b)    {        /* Base case : Both empty */        if (a == null && b == null)        {            return true;        }         // If only one is empty        if (a == null || b == null)        {            return false;        }         /* Both non-empty, compare them recursively        Note that in recursive calls, we pass left        of one tree and right of other tree */        return a.data == b.data && areMirror(a.left, b.right)                            && areMirror(a.right, b.left);    }     // Driver code to test above methods    public static void Main(string[] args)    {        BinaryTree tree = new BinaryTree();        Node a = new Node(1);        Node b = new Node(1);        a.left = new Node(2);        a.right = new Node(3);        a.left.left = new Node(4);        a.left.right = new Node(5);         b.left = new Node(3);        b.right = new Node(2);        b.right.left = new Node(5);        b.right.right = new Node(4);         if (tree.areMirror(a, b) == true)        {            Console.WriteLine("Yes");        }        else        {            Console.WriteLine("No");        }     }} // This code is contributed by Shrikant13
<script>// javascript program to see if two trees// are mirror of each other // A binary tree nodeclass Node {          Node(data) {        this.data = data;        this.left = this.right = null;    }} var a, b;     /*     * Given two trees, return true if they are mirror of each other     */    function areMirror( a,  b) {        /* Base case : Both empty */        if (a == null && b == null)            return true;         // If only one is empty        if (a == null || b == null)            return false;         /*         * Both non-empty, compare them recursively Note that in recursive calls, we         * pass left of one tree and right of other tree         */        return a.data == b.data && areMirror(a.left, b.right) && areMirror(a.right, b.left);    }     // Driver code to test above methods                   a = new Node(1);         b = new Node(1);        left = new Node(2);        right = new Node(3);        left.left = new Node(4);        left.right = new Node(5);         left = new Node(3);        right = new Node(2);        right.left = new Node(5);        right.right = new Node(4);         if (areMirror(a, b) == true)            document.write("Yes");        else            document.write("No"); // This code contributed by umadevi9616</script>
Output : 
Yes
Time Complexity : O(n)Iterative method to check if two trees are mirror of each other 
YouTubeGeeksforGeeks501K subscribersCheck if two trees are Mirror | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UG3OhQ5QRkk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Ashish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
AshishR
shrikanth13
umadevi9616
pravinyakumbhare
anikakapoor
Amazon
Amazon-Question
D-E-Shaw
Hike
MakeMyTrip
STL
Queue
Stack
Tree
Amazon
D-E-Shaw
Hike
MakeMyTrip
Stack
Queue
Tree
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Queue | Set 1 (Introduction and Array Implementation)
Priority Queue | Set 1 (Introduction)
LRU Cache Implementation
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation)
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Program for Tower of Hanoi
Check for Balanced Brackets in an expression (well-formedness) using Stack