-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_35.java
More file actions
66 lines (57 loc) · 2.2 KB
/
Copy pathBT_Problem_35.java
File metadata and controls
66 lines (57 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package trees.binaryTree;
// Tree Isomorphism Problem
public class BT_Problem_35 {
Node root1, root2;
boolean isIsomorphic(Node n1, Node n2)
{
// Both roots are NULL, trees isomorphic by definition
if (n1 == null && n2 == null)
return true;
// Exactly one of the n1 and n2 is NULL, trees not isomorphic
if (n1 == null || n2 == null)
return false;
if (n1.data != n2.data)
return false;
// There are two possible cases for n1 and n2 to be isomorphic
// Case 1: The subtrees rooted at these nodes have NOT been "Flipped".
// Both of these subtrees have to be isomorphic.
// Case 2: The subtrees rooted at these nodes have been "Flipped"
return (
isIsomorphic(n1.left, n2.left)
&&
isIsomorphic(n1.right, n2.right)
)
||
(
isIsomorphic(n1.left, n2.right)
&&
isIsomorphic(n1.right, n2.left)
);
}
// Driver program to test above functions
public static void main(String args[])
{
BT_Problem_35 tree = new BT_Problem_35();
// Let us create trees shown in above diagram
tree.root1 = new Node(1);
tree.root1.left = new Node(2);
tree.root1.right = new Node(3);
tree.root1.left.left = new Node(4);
tree.root1.left.right = new Node(5);
tree.root1.right.left = new Node(6);
tree.root1.left.right.left = new Node(7);
tree.root1.left.right.right = new Node(8);
tree.root2 = new Node(1);
tree.root2.left = new Node(3);
tree.root2.right = new Node(2);
tree.root2.right.left = new Node(4);
tree.root2.right.right = new Node(5);
tree.root2.left.right = new Node(6);
tree.root2.right.right.left = new Node(8);
tree.root2.right.right.right = new Node(7);
if (tree.isIsomorphic(tree.root1, tree.root2) == true)
System.out.println("Yes");
else
System.out.println("No");
}
}