数据结构练习(38)树的子结构

http://zhedahht.blog.163.com/blog/static/25411174201011445550396/

思路:

2个递归,总体来说思路还是比较自然的。但是如何把代码写的优雅,包括一些边界的检查,还是一件需要雕琢的事情。

文章中关于子树判断的递归处理的很好,代码十分精简:

bool DoesTree1HaveAllNodesOfTree2(TreeNode* pTreeHead1, TreeNode* pTreeHead2)
{
        if(pTreeHead2 == NULL)
                return true;
 
        if(pTreeHead1 == NULL)
                return false;
 
        if(pTreeHead1->m_nValue != pTreeHead2->m_nValue)
                return false;
 
        return DoesTree1HaveAllNodesOfTree2(pTreeHead1->m_pLeft, pTreeHead2->m_pLeft) &&
                DoesTree1HaveAllNodesOfTree2(pTreeHead1->m_pRight, pTreeHead2->m_pRight);
}
struct TreeNode {
    int m_value;
    TreeNode* m_lhs;
    TreeNode* m_rhs;
};

bool try2solve(TreeNode* pHead1, TreeNode* pHead2)
{
    if (pHead2 == NULL)
        return true;
    if (pHead1 == NULL)
        return false;

    if (pHead1->m_value != pHead2->m_value)
        return false;

    return try2solve(pHead1->m_lhs, pHead2->m_lhs) && try2solve(pHead1->m_rhs, pHead2->m_rhs);
}

bool HasSubTree(TreeNode* pTreeHead1, TreeNode* pTreeHead2)
{
    if (pTreeHead1 == NULL || pTreeHead2 == NULL)
        return false;

    bool result = false;

    if (pTreeHead1->m_value == pTreeHead2->m_value)
        result = try2solve(pTreeHead1, pTreeHead2);

    if (!result && pTreeHead1->m_lhs)
        result = HasSubTree(pTreeHead1->m_lhs, pTreeHead2);
    if (!result && pTreeHead1->m_rhs)
        result = HasSubTree(pTreeHead1->m_rhs, pTreeHead2);

    return result;
}

 

posted @ 2012-12-21 16:34  kedebug  阅读(224)  评论(0编辑  收藏  举报