3

what will be the algorithm to check two binary tree are isomorphic in nature? my code-

boolean isIsomorphic(Root t1 , Root t2){
    if(t1==null || t2==null){
        return false;
    }

    if((t1.value == t2.value) && (isIsomorphic(t1.left,t2.right) && isIsomorphic(t1.right,t2.left))) {
        return true
    }

    return false; 
}
huon
  • 94,605
  • 21
  • 231
  • 225
Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128

2 Answers2

3

The wikipedia article for 'isomorphism' says that "if two objects are isomorphic, then any property that is preserved by an isomorphism and that is true of one of the objects, is also true of the other."

So your question needs to state whether you care about shape, data, performance, etc.

If you care about the behavior of the binary tree for search, your algorithm is not correct. See What does it mean for two binary trees to be isomorphic?

The simplest way to check for isomorphism is doing an in-order-traversal of the two trees, checking the values after each step.

On the other hand, if you care about shape and data, @amits fixes will get that for you. But note that you might as well call it an exact match.

Finally, if you only care about shape, then you need to drop your checks t1.value == t2.value

Community
  • 1
  • 1
Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52
  • I think this does not align with the definition of [graph isomorphism](http://en.wikipedia.org/wiki/Graph_isomorphism) – amit Apr 27 '12 at 15:42
  • 1
    @amit The more I look around, the more I agree with you about this problem not being specific enough. See http://tech-queries.blogspot.com/2010/04/isomorphic-trees.html which says "Two binary trees s and t are isomorphic if they have the same shape; the values stored in the nodes do not affect whether two trees are isomorphic". I will update my post to differentiate between the two conflicting definitions of isomorphic. – Dilum Ranatunga Apr 27 '12 at 15:47
0

From here:Two trees s and t are quasi-isomorphic if s can be transformed into t by swapping left and right children of some of the nodes of s. The values in the nodes are not important in determining quasi-isomorphism, only the shape is important.

The link also provides code for this definition of isomorphic.

If the values are important, the approach could be as follows:

  1. Perform a level-by-level traversal of each tree using two queues
  2. After you have finished adding a level in both trees, check queue size. If different, report 'NOT ISOMORPHIC'
  3. Otherwise, for the first first tree, dequeue all nodes in that level into a set.
  4. For the second tree, dequeue each node and check if it exists in the set.
  5. If set membership test fails, report 'NOT ISOMORPHIC'.
  6. If we finish all levels, report ISOMORPHIC.
curryage
  • 481
  • 1
  • 6
  • 19