求解(树的子结构问题-何海涛100题)

下面的题目是看何海涛100题中遇到的,自己看不懂,特贴出来请大家帮忙。原文地址为http://zhedahht.blog.163.com/blog/static/25411174201011445550396/

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

题目:二叉树的结点定义如下:

struct TreeNode

{

        int m_nValue;

        TreeNode* m_pLeft;

        TreeNode* m_pRight;

};

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

例如,下图中的两棵树AB,由于A中有一部分子树的结构和B是一样的,因此B就是A的子结构。

                 1                                                   8
               /    \                                               /    \
              8    7                                             9    2
            /    \
           9    2
                /  \
               4  7

bool HasSubtree(TreeNode* pTreeHead1, TreeNode* pTreeHead2)

{

        if((pTreeHead1 == NULL && pTreeHead2 != NULL) ||

                (pTreeHead1 != NULL && pTreeHead2 == NULL))

                return false;

 

        if(pTreeHead1 == NULL && pTreeHead2 == NULL)

                return true;

 

        return HasSubtreeCore(pTreeHead1, pTreeHead2);

}

bool HasSubtreeCore(TreeNode* pTreeHead1, TreeNode* pTreeHead2)

{

        bool result = false;

        if(pTreeHead1->m_nValue == pTreeHead2->m_nValue)

        {

                result = DoesTree1HaveAllNodesOfTree2(pTreeHead1, pTreeHead2);

        }

 

        if(!result && pTreeHead1->m_pLeft != NULL)

                result = HasSubtreeCore(pTreeHead1->m_pLeft, pTreeHead2);

 

        if(!result && pTreeHead1->m_pRight != NULL)

                result = HasSubtreeCore(pTreeHead1->m_pRight, pTreeHead2);

 

        return result;

}


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

}

接触C++虽然有一段时间了,但是上面的程序依然有地方看不懂,请师兄师姐学者指导!

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值