If we have two trees then to find out if these are isomorphic to each other or not?
This question is asked in many company written exams many times.
To understand this problem we have to first understand what isIsomorphic.

Two trees are called Isomorphic only and only if both trees are mirror image of each other from every node.
So i wrote a function called isIsomorphic . this will return one if both trees are isomorphic and 0 if both are not isomorphic.

static int isIsomorphic(Node root1,Node root2) {
/*
For your reference:
class Node {
	Node left, right;
	int val;
	Node() {
	left = right = null;
	}
}
The structure has already been declared. You can start creating nodes by Node x = new Node()
*/ 
    int result =0;
//Check if both trees are null
    if(root1==null&& root2==null){
        result=1;
    }
    //if only null
    else if(root1==null ||root2==null){
        result=0;
    }
    //if both are not null
    else{
        //if((root1.val == root2.val) && (isIsomorphic(root1.left,root2.right)==1 && isIsomorphic(root1.right,root2.left)==1)) {
       //     result=1;
        //}
        if(root1.val == root2.val)
           {
               if((root1.left.val==root2.right.val)&&(root1.left.val==root2.right.val))
               {
                   if(isIsomorphic(root1.left.left,root2.right.left)==1 &&isIsomorphic(root1.left.right,root2.right.right)==1)
                       result=1;
               }
           }
       }

      return result;
    
}

I dont know if that is right. Something can be missing. I will welcome any suggestion.

The following two tabs change content below.
He is founder and CTO of Habilelabs.io. He senior software architect. He is guru of various Mobile and web technologies including Node.js, Angular.js, Meteor.js. He is founder member of habilelabs Pvt. Ltd.