题目:输入两颗二叉树A和B,判断B是不是A的子结构
算法思想很简单:首先在A中找到和B的根节点的值一样的节点R,然后再判断树A中以R为根节点的子树是不是包含和树B一样的结构。
bool HasSubTree(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2)
{
bool result=false;
if(pRoot1!=NULL && pRoot2!=NULL)
{
if(pRoot1->m_nValue==pRoot2->m_nValue)
{
result=DoesTree1HaveTree2(pRoot1,pRoot2);
}
if(!result)
{
result=HasSubtree(pRoot1->m_pLeft,pRoot2);
}
if(!result)
{
result=HasSubtree(pRoot1->m_pRight,pRoot2);
}
}
return result;
}
bool DoesTree1HaveTree2(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2)
{
if(pRoot2==NULL)
{
return true;
}
if(pRoot1==NULL)
{
return false;
}
if(pRoot1->m_nValue!=pRoot2->m_nValue)
{
return false;
}
return DoesTree1HaveTree2(pRoot1->m_pLeft,pRoot2->m_pLeft) && DoesTree1HaveTree2(pRoot1->m_pRight,pRoot2->m_pRight);
}