Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to check if 2 given binary trees are isomorphic or not
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.util.*;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to check if 2 given trees are isomorphic to each other
- static boolean isomorphic_tree(node root1, node root2){
- // if both the nodes are null then return true
- if (root1 == null && root2 == null){
- return true;
- }
- // if any one of them is null then return false
- if (root1 == null || root2 == null){
- return false;
- }
- // if the data fields are not equal then return false
- if (root1.data != root2.data){
- return false;
- }
- // else check if the left and the right subtrees are isomorphic recursively
- return (
- ( isomorphic_tree(root1.left, root2.left) && isomorphic_tree(root1.right, root2.right) ) ||
- ( isomorphic_tree(root1.left, root2.right) && isomorphic_tree(root1.right, root2.left) )
- );
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- node head2 = new node(5);
- head2.left = new node(2);
- head2.right = new node(12);
- head2.left.left = new node(-4);
- head2.left.right = new node(3);
- head2.right.left = new node(9);
- head2.right.right = new node(21);
- head2.right.right.left = new node(19);
- head2.right.right.right = new node(25);
- node i1 = new node(1);
- i1.left = new node(2);
- i1.right = new node(3);
- i1.left.left = new node(4);
- i1.left.right = new node(5);
- i1.right.left = new node(6);
- i1.left.right.left = new node(7);
- i1.left.right.right = new node(8);
- node i2 = new node(1);
- i2.left = new node(3);
- i2.right = new node(2);
- i2.right.left = new node(4);
- i2.right.right = new node(5);
- i2.left.right = new node(6);
- i2.right.right.right = new node(7);
- i2.right.right.left = new node(8);
- System.out.println("TREE #1 and TREE #2 are isomorphic : " + isomorphic_tree(head, head2));
- System.out.println("TREE #3 and TREE #4 are isomorphic : " + isomorphic_tree(i1, i2));
- }
- }
Add Comment
Please, Sign In to add comment