Skip to content

Instantly share code, notes, and snippets.

@novoland
Forked from anonymous/is_subtree.cpp
Last active August 29, 2015 14:06
Show Gist options
  • Save novoland/933e0a92c3e5c7d0217c to your computer and use it in GitHub Desktop.
Save novoland/933e0a92c3e5c7d0217c to your computer and use it in GitHub Desktop.
// check sub tree n1 == sub tree n2
bool isSame(const TreeNode* n1, const TreeNode* n2){
if( n1 == NULL && n2 == NULL )
return true;
if( n1 == NULL || n2 == NULL )
return false;
if( n1->data != n2->data )
return false;
return isSame(n1->leftChild, n2->leftChild) && isSame(n1->rightChild, n2->rightChild);
}
bool isSubTree(const TreeNode *n1, const TreeNode *n2){
if( n1 == NULL){
return false; // the bigger tree is empty, so t2 is not subtree of t1
}
if( n1->data == n2->data){
if( isSame(n1, n2))
return true;
}
return isSubTree(n1->leftChild, n2) || isSubTree(n2->rightChild, n2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment