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.
- 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.
Code in C based on Above approach
struct node* left;
struct node* right;
struct node* newNode(int data)
struct node* node = (struct node*)
node->data = data;
node->left = NULL;
node->right = NULL;
int identicalTrees(struct node* a, struct node* b)
if (a==NULL && b==NULL)
if (a!=NULL && b!=NULL)
a->data == b->data &&
identicalTrees(a->left, b->left) &&
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);
printf("Both tree are identical.");
printf("Trees are not identical.");
Both tree are identical