Monday, August 15, 2011

Check if a binary tree is subtree of another binary tree

Source

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.


bool isMatch(node* pSubTree, node* pTree)
{

if ((pSubTree == NULL) && (pTree == NULL)) {

return true;

}

if ((pSubTree == NULL) || (pTree == NULL)) {

return false;

}

return ((pSubTree->data == pTree->data) && isMatch(pSubTree->left, pTree->left) && isMatch(pSubTree->right, ptree->right)) ;



}
bool isSubTree(node* pSubTree, node* pTree)
{
if (pSubTree == NULL) {
return true;

}


if (pTree == NULL) {
return false;

}


return (isMatch(pSubTree, pTree) || isSubTree(pSubTree, pTree->left) || isSubTree(pSubTree, pTree->right));

}

No comments:

Post a Comment