18. 树的子结构

题目描述

输入两颗二叉树A,B,判断B是不是A的子结构。

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

解析

递归调用HasSubtree遍历二叉树A,如果发现某一结点的值与树B的头结点的值相同,则调用DoesTree1HaveTree2,判断以这两个相等结点为根结点的树,是否相等(根结点值相等,左子树相等,右子树相等)

实现

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);
}

你可能感兴趣的:(18. 树的子结构)