Description: 2 trees are said to be identical if they have the same data and structure. Given 2 trees, we have to check if they are identical. We return 1 if the trees are identical, else we return 0.

 
If video does not load, Click here
 
Example:

The following trees are identical:

 

The following trees are not identical:

Algorithm and implementation:

 

/*The following function returns 1 if the trees are identical. Else, we return 0. */

int checkidentical(struct node* node1, struct node*node2)

{

 

   if (node1==NULL && node2==NULL)

       return 1;/*if both empty*/

   if (node1!=NULL && node2!=NULL)

   {

       return

       (

           node1->data == node2->data && /*data should be same*/

           checkidentical (node1->left, node2->left) && /*left subtrees should be identical*/

           checkidentical(node1->right, node2->right) /*right subtrees should be identical*/

      );

  }  

   return 0;/*one of them is null*/

}

Go to top