1.题目描述:
输入两棵二叉树A和B,判断B是不是A的子结构。二叉树结点的定义如下:
struct BinaryTreeNode
{
char m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
2.分析:
1)第一步:在树A种找到和B的根结点的值一样的结点R;
2)第二部:判断A中以R为根结点的子树是不是包含和树B一样的结构。
3.源代码:
typedef struct BinaryTreeNode
{
char m_nValue;
struct BinaryTreeNode* m_pLeft;
struct BinaryTreeNode* m_pRight;
}*BinaryTree;
void CreateTree(BinaryTree &T)
{
char data;
cin>>data;
if(data=='*')
T=NULL;
else
{
T = (BinaryTree)malloc(sizeof(BinaryTreeNode));
T->m_nValue = data;
CreateTree(T->m_pLeft);
CreateTree(T->m_pRight);
}
}
void Print(BinaryTree T)
{
if(T)
{
cout<<T->m_nValue<<endl;
Print(T->m_pLeft);
Print(T->m_pRight);
}
}
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);
}
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;
}
int main(int argc,char *argv[]){
bool result = false;
BinaryTree T1,T2;
cout<<"以先序遍历的顺序创建的二叉树T1:"<<endl;
CreateTree(T1);
cout<<"原始的二叉树T1的先序遍历序列为:"<<endl;
Print(T1);
cout<<"以先序遍历的顺序创建的二叉树T2:"<<endl;
CreateTree(T2);
cout<<"原始的二叉树T2的先序遍历序列为:"<<endl;
Print(T2);
if(HasSubtree(T1, T2))
{
result = true;
cout<<"T1中包含T2子树"<<endl;
}
else
cout<<"T1中不包含T2子树"<<endl;
return 0;
}
4.运行过程:
以先序遍历的顺序创建的二叉树T2:
124**5**3**
原始的二叉树T1的先序遍历序列为:
1
2
4
5
3
以先序遍历的顺序创建的二叉树T2:
24**5**
原始的二叉树T2的先序遍历序列为:
2
4
5
T1中包含T2子树
Program ended with exit code: 0