题目:输入两棵二叉树A和B,判断B是不是A的子结构。二叉树结点的定义如下:

struct BinaryTreeNode
{
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};

分析:要查找树A中是否存在B子结构,分成两步进行:第一步在树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=DoseTree1HaveTree2(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 DoseTree1HaveTree2(pRoot1->m_pLeft,pRoot2->m-pLeft)&&DoseTree1HaveTree2(pRoot1->m_pRight,pRoot2->m-pRight);
}