Check if a binary tree is subtree of another binary tree
PROBLEM :
Given two binary trees, check if the first tree is subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.
For example, in the following case, tree S is a subtree of tree T.
Tree S
10
/ \
4 6
\
30
Tree T
26
/ \
10 3
/ \ \
4 6 3
\
30
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;------------------------------*/
int subtree(tree *root1,tree *root2)
{
if(root2==NULL)
return 1 ;
if(root1==NULL)
return 0 ;
if(check_identical(root1,root2))
return 1 ;
else
return(subtree(root1->left,root2)||subtree(root1->right,root2)) ;
}
int check_identical(tree *root1,tree *root2)
{
int a,b ;
if(root1==NULL&&root2==NULL)
return 1 ;
else
{
if(root1->info==root2->info)
{
a=check_identical(root1->left,root2->left) ;
b=check_identical(root1->right,root2->right) ;
}
else
return 0 ;
}
if(a==1&&b==1)
return 1 ;
}
---------------------------------------------------------------------------------
Given two binary trees, check if the first tree is subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.
For example, in the following case, tree S is a subtree of tree T.
Tree S
10
/ \
4 6
\
30
Tree T
26
/ \
10 3
/ \ \
4 6 3
\
30
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;------------------------------*/
int subtree(tree *root1,tree *root2)
{
if(root2==NULL)
return 1 ;
if(root1==NULL)
return 0 ;
if(check_identical(root1,root2))
return 1 ;
else
return(subtree(root1->left,root2)||subtree(root1->right,root2)) ;
}
int check_identical(tree *root1,tree *root2)
{
int a,b ;
if(root1==NULL&&root2==NULL)
return 1 ;
else
{
if(root1->info==root2->info)
{
a=check_identical(root1->left,root2->left) ;
b=check_identical(root1->right,root2->right) ;
}
else
return 0 ;
}
if(a==1&&b==1)
return 1 ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment