Showing posts with label binary tree c language. Show all posts
Showing posts with label binary tree c language. Show all posts

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. 

C Program To Find Height/Depth Of Binary Tree [ How To ]

What Is Height/Depth Of A Binary Tree?

 A binary tree of height  h ( > 0 ), has at least h elements and at most (2^h -1) elements in it.


C Program Code To Find Height/Depth Of a Tree:

int binary_tree_height ( mynode *p )
{
  if ( p == NULL )
return ( 0 );

if ( p->left )
h1 = binary_tree_height ( p->left );

if ( p->right )
h2 = binary_tree_height ( p->right );

return ( max ( h1, h2 ) + 1 );
} 


When You invoke this recursive function, it will return height/depth of a binary tree.

Share This