Skip to content

Commit 923ce8a

Browse files
committed
isomorphic tree
1 parent 26dad0e commit 923ce8a

File tree

2 files changed

+70
-36
lines changed

2 files changed

+70
-36
lines changed

Trees/btree.java

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +0,0 @@
1-
2-
class Node
3-
{
4-
int data;
5-
Node left;
6-
Node right;
7-
Node(int data)
8-
{
9-
this.data=data;
10-
left=right=null;
11-
}
12-
}
13-
14-
class BinaryTree{
15-
Node root;
16-
BinaryTree()
17-
{
18-
root = null;
19-
}
20-
BinaryTree(int data)
21-
{
22-
this.root=new Node(data);
23-
}
24-
}
25-
26-
class btree{
27-
public static void main(String[] args) {
28-
29-
BinaryTree bt=new BinaryTree(2);
30-
bt.root.left=new Node(3);
31-
bt.root.right=new Node(5);
32-
bt.root.left.right=new Node(9);
33-
bt.root.right.left=new Node(7);
34-
35-
}
36-
}

Trees/isomorphicBtree.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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

Comments
 (0)