#include<iostream>
#include<queue>
using namespace std;
typedef struct TreeNode
{
int data;
TreeNode* lchild;
TreeNode* rchild;
}BiNode,*Bitree;
queue<Bitree> bt;
int height=0;
//建树,先序遍历
void Creat_bitree(Bitree &t)
{
t=new TreeNode;
//t=(Bitree)malloc(sizeof(BiNode));
int ch;
cin>>ch;
if(ch==-1){
t=NULL;
return;
}
else{
t->data=ch;
Creat_bitree(t->lchild);
Creat_bitree(t->rchild);
}
return ;
}
//计算树的高度
int Height(Bitree root)
{
if(root==NULL)
return 0;
int h=max(Height(root->lchild),Height(root->rchild))+1;
if(h>=height)
bt.push(root);
return h;
}
//判断树结点是否相同
bool isSame(Bitree s,Bitree t)
{
if(t==NULL)
return true;
else if(s==NULL&&t!=NULL)
return false;
else if(t->data!=s->data)
return false;
return isSame(s->lchild,t->lchild)&&isSame(s->rchild,t->rchild);
}
//判断树t是否为树s的子树
bool isSubTree(Bitree s,Bitree t)
{
height=Height(t); //求t树的高度
int k=Height(s); //用队列保存s树所有高度与t树相同的子树根节点
while(!bt.empty()){
Bitree root=bt.front();
bt.pop();
if(isSame(root,t))
return true;
}
return false;
}
int main()
{
Bitree s,t; //判断t是不是s的子树
cout<<"建立s树:";
Creat_bitree(s);
cout<<"建立t树:";
Creat_bitree(t);
bool isSub=isSubTree(s,t);
if(isSub)
cout<<"二叉树t是二叉树s的子结构!";
else
cout<<"二叉树t不是二叉树s的子结构!";
return 0;
}
判断一个树是否是另一个树的子结构(c++实现)
猜你喜欢
转载自blog.csdn.net/qq_43710881/article/details/106934466
今日推荐
周排行