Tuesday, 30 June 2015

Check If Both Binary Trees Are Identical

Complexity O(m) where m is size of tree with nodes m <=n , where n is size of other tree

#include<stdio.h>


#include<stdlib.h>


struct treeNode
{
    int data;
    struct treeNode* left;
    struct treeNode* right;

};


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

}

int isIdentical(struct treeNode* A, struct treeNode* B)
{
    //if both are empty , return 1
    if (A == NULL  && B == NULL)
    {
        return 1;
           
    }

    if(A != NULL && B != NULL)
    {
        //check if the data at root or root of subtree (while recursion) , and left and right subtree are equal
        //by recursing to left and right subtree
        return A->data == B->data && isIdentical(A->left, B->left) && isIdentical(A->right, B->right);
    }
    //else both trees are not identical ,one empty and other is not ,  return 0
    else return 0;
}

int main()
{
    struct treeNode *root1 = newNode(1);
    struct treeNode *root2 = newNode(1);
    root1->left = newNode(2);
    root1->right = newNode(3);
    root1->left->left = newNode(4);
    root1->left->right = newNode(5);

    root2->left = newNode(2);
    root2->right = newNode(3);
    root2->left->left = newNode(4);
    root2->left->right = newNode(5);

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

    getchar();
    return 0;
}

No comments:

Post a Comment