标签:二叉树
题目
输入两颗二叉树A和B,判断B是不是A的子结构.二叉树结点的定义如下:
先在A中找B的跟节点,若找到相同的,在判断左右子树是否相同.
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode(int n) : m_nValue(n), m_pLeft(NULL), m_pRight(NULL) {};
};
bool HasSubtree(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2);
bool DoesTree1HaveTree2(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2);
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);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:二叉树
原文地址:http://blog.csdn.net/nizhannizhan/article/details/47762879