1
+
2
+ class Node {
3
+ int data ;
4
+ Node left ;
5
+ Node right ;
6
+
7
+ Node (int data ) {
8
+ this .data = data ;
9
+ left = right = null ;
10
+ }
11
+ }
12
+
13
+ class BinaryTree {
14
+ Node root ;
15
+
16
+ BinaryTree () {
17
+ root = null ;
18
+ }
19
+
20
+ BinaryTree (int data ) {
21
+ this .root = new Node (data );
22
+ }
23
+
24
+ boolean isIsomorphic (Node root1 , Node root2 )
25
+ {
26
+ if (root1 ==null && root2 ==null )
27
+ return true ;
28
+ if (root1 ==null ||root2 ==null )
29
+ return false ;
30
+ // if(root1.data!=root2.data)
31
+ // return false;
32
+ // return (isIsomorphic(root1.left,root2.left) &&
33
+ // isIsomorphic(root1.right,root2.right))
34
+ // || (isIsomorphic(root1.left,root2.right) &&
35
+ // isIsomorphic(root1.right,root2.left));
36
+
37
+ return root1 .data ==root2 .data &&
38
+ ((isIsomorphic (root1 .left ,root2 .left ) && isIsomorphic (root1 .right ,root2 .right ))
39
+ || (isIsomorphic (root1 .left ,root2 .right ) && isIsomorphic (root1 .right ,root2 .left ))
40
+ );
41
+ }
42
+ }
43
+
44
+ class isomorphicBtree {
45
+ public static void main (String [] args ) {
46
+
47
+ BinaryTree bt = new BinaryTree (2 );
48
+ bt .root .left = new Node (3 );
49
+ bt .root .right = new Node (5 );
50
+ bt .root .left .right = new Node (9 );
51
+ bt .root .right .left = new Node (7 );
52
+
53
+ BinaryTree bt2 = new BinaryTree (2 );// BT with root node 2
54
+ bt2 .root .left = new Node (5 );// linking explicitly
55
+ bt2 .root .right = new Node (3 );
56
+ bt2 .root .left .right = new Node (7 );
57
+ bt2 .root .right .left = new Node (9 );
58
+
59
+ BinaryTree bt3 = new BinaryTree (2 );// BT with root node 2
60
+ bt3 .root .left = new Node (3 );// linking explicitly
61
+ bt3 .root .right = new Node (5 );
62
+ bt3 .root .left .left = new Node (7 );
63
+ // bt3.root.right.left=new Node(7);
64
+ bt3 .root .right .right = new Node (9 );
65
+
66
+ System .out .println ("isIsomorphic:" +bt .isIsomorphic (bt .root , bt2 .root ));
67
+ System .out .println ("isIsomorphic:" + bt .isIsomorphic (bt .root , bt3 .root ));
68
+
69
+ }
70
+ }
0 commit comments