Monday, July 22, 2013

C Code To Find If Two Binary Trees Are Identical

How To Find If Two Binary Trees Are Identical?

If the two trees have same structure and data in corresponding nodes must be equal then the two binary trees are identical.


C Code To Find If Two Binary Trees Are Identical:

#define IDENTICAL 0
#define NOT_IDENTICAL 1

int identical ( struct node* a, struct node* b ) 

if ( a == NULL && b == NULL )
{
return ( IDENTICAL );
}
else if (a != NULL && b != NULL ) 

return(  ( a->data == b->data )  && identical ( a->left, b->left ) &&  identical( a->right, b->right ) ); 

else
{
return( NOT_IDENTICAL ); 
}
}

On invoking this recursive function, it will return 0 or 1 based on the two binary trees passed to the function. 

Share This