top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a function to find whether two binary tree are mirror image of each other or not?

+5 votes
734 views
Write a function to find whether two binary tree are mirror image of each other or not?
posted Apr 23, 2016 by Ajay Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Objective: - Given two binary trees check if they are mir­ror image of each other

Example:
enter image description here

Approach:

Do the pre­order tra­ver­sal on both the trees simultaneously.

if any node doesn’t have corresponding node in the another tree, return false.

check if left node in one tree is the right node in another tree, and vice verse.

Code:

public class CheckMirrorTree {

    public boolean checkMirror(Node root1, Node root2) {
        if (root1 == null && root2 == null) {
            return true;
        }
                if(root1.data !=root2.data){
                        return false;
                }

        if ((root1 == null && root2 != null)
                || (root1 != null && root2 == null)) { // if any node doesn't
            // have corresponding node in the another tree, return false
            return false;
        }
        // check if left node in one tree is the right node in another tree, and
        // vice versa
        return checkMirror(root1.left, root2.right)
                && checkMirror(root1.right, root2.left);

    }

    public static void main(String[] args) {
        Node root1 = new Node(1);
        root1.left = new Node(2);
        root1.left.right = new Node(3);
        root1.right = new Node(4);

        Node root2 = new Node(1);
        root2.right = new Node(2);
        root2.right.left = new Node(3);
        root2.left = new Node(4);

        CheckMirrorTree i = new CheckMirrorTree();
        System.out.println("Is Mirror Trees : " + i.checkMirror(root1, root2));

    }

}

class Node {
    int data;
    Node left, right;

    public Node(int data) {
        this.data = data;
    }
}
answer Apr 26, 2016 by Manikandan J
Similar Questions
+6 votes
                    50                      50
                   /  \                    /  \
                  20     30              30   20
Sample Tree<---   /  \                       /  \   ----> Mirror image
               70      80                   80   70
              /  \    \                    /    /  \  
             10  40     60                60   40   10
+2 votes

How to find the smallest element in a Binary Tree (Not BST)? Sample C/C++ code would be helpful.

...