Write a program to determine if Two Trees are Identical

Two trees are identical if they have same data and arrangement of node is also same.

To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees.

Algorithm :
Use preorder tree traversal and compare data .

Code :

int identicalTrees(struct node* tree1, struct node* tree2)
{
    /*1. both empty */
    if (tree1==NULL && tree2==NULL)
        return 1;
 
    /* 2. both non-empty -> compare them */
    else if (tree1!=NULL && tree2!=NULL)
   {
        return
        (
            tree1->data == tree2->data &&
            identicalTrees(tree1->left, tree2->left) &&
            identicalTrees(tree1->right, tree2->right)
        );
    }
    /* 3. one empty, one not -> false */
    else return 0;
} 

Leave a Reply

Your email address will not be published. Required fields are marked *

For Inserting code :
Paste your code in the comment form, select it and then click the language link

C | C++ | Java |

*