Site icon

Check given binary trees are Isomorphic in java (recursive / examples)

Examples – Check given binary tree is Isomorphic of other binary tree in java

Example 1: check binary trees are Isomorphic shown in Fig 1.

Fig 1: Identical binary trees

Example 2: check binary trees are Isomorphic shown in Fig 2.

Fig 2: Example of isomorphic binary tree

Example 3: check binary trees are Isomorphic shown in Fig 3.

Fig 3: Binary trees are not isomorphic

Conclusion: If structure (We will ignore data of nodes) of binary trees is same then binary tree are isomorphic.

Algorithm – check binary trees are Isomorphic.

Program – find if given binary trees are Isomorphic using java

1.) IsomorphicBinaryTree Class: 

package org.learn.Question;

public class IsomorphicBinaryTree {

	public static boolean isIsomorphicBinaryTree(Node tree1, Node tree2) {

		if (tree1 == null && tree2 == null) {
			return true;
		}

		if (tree1 == null || tree2 == null) {
			return false;
		}

		if (false == isIsomorphicBinaryTree(tree1.left, tree2.left))
			return false;

		if (false == isIsomorphicBinaryTree(tree1.right, tree2.right))
			return false;

		return true;
	}
}

2.) App Class:

package org.learn.Client;

import org.learn.Question.IsomorphicBinaryTree;
import org.learn.Question.Node;

public class App 
{
	public static void main( String[] args )
    {		
		Node tree1 = Node.createNode(50);
		tree1.left = Node.createNode(30);
		tree1.right = Node.createNode(30);
		// left sub tree
		tree1.left.left = Node.createNode(40);
		tree1.left.right = Node.createNode(10);

		// right subtree
		tree1.right.left = Node.createNode(30);
		tree1.right.right = Node.createNode(60);
		
		Node tree2 = Node.createNode(10);
		tree2.left = Node.createNode(40);
		tree2.right = Node.createNode(20);
		// left sub tree
		tree2.left.left = Node.createNode(50);
		tree2.left.right = Node.createNode(15);

		// right subtree
		tree2.right.left = Node.createNode(70);
		tree2.right.right = Node.createNode(60);

		boolean isSame = IsomorphicBinaryTree.isIsomorphicBinaryTree(tree1, tree2);
		if(isSame) {
			System.out.println("Binary trees are Isomorphic");
		} else {
			System.out.println("Binary trees are not Isomorphic");
		}
    }
}

3.) Node Class :

package org.learn.Question;

public class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int num) {
		this.data = num;
		this.left = null;
		this.right = null;
	}

	public Node() {
		this.left = null;
		this.right = null;
	}

	public static Node createNode(int number) {
		return new Node(number);
	}
}

Output – check given binary trees (Fig 1) are Isomorphic using java

Binary trees are Isomorphic

Download code – isomorphic binary trees in java

 

Exit mobile version