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 identical or not
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.lang.reflect.Array;
- import java.util.*;
- import static java.lang.Integer.max;
- // 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 identical to each other
- static boolean isIdentical(node root1, node root2){
- // if both the nodes are null then return true
- if (root1 == null && root2 == null){
- return true;
- }
- // if the node are not null then check
- // 1. do nodes have same data
- // 2. do the have identical left subtrees
- // 3. do the have identical right subtrees
- if (root1 != null && root2 != null){
- return (
- root1.data == root2.data &&
- isIdentical(root1.left, root2.left) &&
- isIdentical(root1.right, root2.right)
- );
- }
- return false;
- }
- 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 head3 = new node(1);
- head3.left = new node(2);
- head3.right = new node(3);
- head3.left.left = new node(4);
- head3.left.right = new node(5);
- head3.right.right = new node(6);
- head3.left.left.right = new node(7);
- head3.right.right.left = new node(8);
- head3.left.left.right.left = new node(9);
- head3.left.left.right.left.left = new node(10);
- head3.right.right.left.right = new node(11);
- System.out.println("TREE #1 and TREE #2 are identical : " + isIdentical(head, head2));
- System.out.println("TREE #1 and TREE #3 are identical : " + isIdentical(head, head3));
- }
- }
Add Comment
Please, Sign In to add comment