Question

Given two binary tree, can you determine if they are identical or not? Write a program...

Given two binary tree, can you determine if they are identical or not? Write a program for that.
Algorithm:
a) If both trees are NULL then return true
b) If both trees are not NULL then, return TRUE if they are
identical.


In java.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

class Node {
   int data;
   Node left, right;

   public Node(int item) {
       data = item;
       left = right = null;
   }
}

class BST {

   Node root;

   BST() {
       root = null;
   }

  
   Node insert(Node root, int data) {

       // If the root is null than tree is empty, new node will become root
       if (root == null) {
           root = new Node(data);
           return root;
       }

       // if data is < root go left
       if (data < root.data)
           root.left = insert(root.left, data);
       // if data > root go right
       else if (data > root.data)
           root.right = insert(root.right, data);

       return root;
   }
   public boolean isIdentical(Node a, Node b)
   {
   //If both trees are empty than return true
   if (a == null && b == null)
   return true;
  
   // non empty than compare the data of each node
   // by iterating the left and right sub tree
   if (a != null && b != null)
   {
   return isIdentical(a.left, b.left) && isIdentical(a.right, b.right) && a.data == b.data ;
     
   }
   return false;
  
   }
}
public class BstIdentical{
   public static void main(String[] args) {
       BST tree = new BST();
       tree.root=tree.insert(tree.root, 10);
       tree.root=tree.insert(tree.root, 15);
       tree.root=tree.insert(tree.root, 12);
       tree.root=tree.insert(tree.root, 8);
      
       BST tree1 = new BST();
       tree1.root=tree1.insert(tree1.root, 10);
       tree1.root=tree1.insert(tree1.root, 15);
       tree1.root=tree1.insert(tree1.root, 12);
       tree1.root=tree1.insert(tree1.root, 8);
       //compring the both tres
       System.out.println(tree.isIdentical(tree.root,tree1.root));
      
   }
}

Note : Please comment below if you have concerns. I am here to help you

If you like my answer please rate and help me it is very Imp for me

Add a comment
Know the answer?
Add Answer to:
Given two binary tree, can you determine if they are identical or not? Write a program...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT