Check whether two binary trees are identical or not in C

Two Binary Trees are Identical or Not ?

Here, in this page we are given root nodes of two trees and we need to find that whether the trees are identical or not.
Trees being identical means that they are same in terms of structures, same in terms of the number of nodes and also same in terms of links.

two trees are identical or not

Algorithm :

 

  • Check whether the data of root nodes of both are same or not.
  • Do this recursively for left subtree and right subtree.
  • Check for corner cases, like when one of the node is absent in the trees ans so on.
binary trees are identical or not in C

Code in C based on Above approach

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node* left;
struct node* right;
};

struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

int identicalTrees(struct node* a, struct node* b)
{
if (a==NULL && b==NULL)
return 1;

if (a!=NULL && b!=NULL)
{
return
(
a->data == b->data &&
identicalTrees(a->left, b->left) &&
identicalTrees(a->right, b->right)
);
}

return 0;
}

int main()
{
struct node *root1 = newNode(10);
struct node *root2 = newNode(10);
root1->left = newNode(20);
root1->right = newNode(30);
root1->left->left = newNode(40);
root1->left->right = newNode(50);

root2->left = newNode(20);
root2->right = newNode(30);
root2->left->left = newNode(40);
root2->left->right = newNode(50);

if(identicalTrees(root1, root2))
printf("Both tree are identical.");
else
printf("Trees are not identical.");

getchar();
return 0;
}
Output :

Both tree are identical